<template>
    <div class="daily-report-system">
        <!-- 左侧导航栏 -->
        <div class="sidebar">
            <!-- 标签页 -->
            <div class="tab-container">
                <el-tabs v-model="activeTab" class="tabs">
                    <el-tab-pane label="草稿箱" :name="1"></el-tab-pane>
                    <el-tab-pane label="已提交" :name="2"></el-tab-pane>
                    <el-tab-pane label="全部日报" :name="3">
                        <!-- 去掉嵌套的已读未读筛选标签页 -->
                    </el-tab-pane>
                </el-tabs>

                <!-- 过滤条件 -->
                <div class="filter-container">
                    <div class="filter-header" @click="toggleFilter">
                        <div class="filter-title-section">
                            <el-icon class="filter-icon"><Filter /></el-icon>
                            <span class="filter-title">筛选条件</span>
                        </div>
                        <el-icon
                            :class="['filter-toggle-icon', { 'is-expanded': isFilterExpanded }]">
                            <ArrowDown />
                        </el-icon>
                    </div>

                    <!-- 展开的筛选内容 -->
                    <div v-show="isFilterExpanded" class="filter-content">
                        <div class="filter-item">
                            <label class="filter-label">月份筛选</label>
                            <el-date-picker
                                v-model="selectedMonth"
                                type="month"
                                placeholder="选择月份"
                                format="YYYY-MM"
                                value-format="YYYY-MM"
                                @change="filterMonth"
                                class="filter-input"
                                :clearable="true" />
                        </div>

                        <div v-if="activeTab === 3" class="filter-item">
                            <label class="filter-label">部门筛选</label>
                            <el-select
                                v-model="selectedDepartment"
                                placeholder="选择部门"
                                @change="filterByDepartment"
                                class="filter-input"
                                clearable>
                                <el-option label="全部部门" value="all"></el-option>
                                <el-option v-for="dept in departments" :key="dept.value" :label="dept.label"
                                    :value="dept.value"></el-option>
                            </el-select>
                        </div>

                        <div v-if="activeTab === 3" class="filter-item">
                            <label class="filter-label">编写人筛选</label>
                            <el-select
                                v-model="selectedAuthor"
                                filterable
                                remote
                                @change="filterAuthors"
                                :loading="authorLoading"
                                class="filter-input"
                                clearable>
                                <el-option label="全部人员" value="all"></el-option>
                                <el-option v-for="author in staffList" :key="author.id" :label="author.name"
                                    :value="author.name">
                                </el-option>
                            </el-select>
                        </div>

                        <div class="filter-actions">
                            <el-button
                                @click="clearFilters"
                                class="clear-btn">
                                重置筛选
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 日报列表 -->
            <div class="report-list-container">
                <div class="new-report-btn-container">
                    <el-button type="primary" @click="createNewReport" class="new-report-btn">
                        <el-icon class="btn-icon">
                            <Plus />
                        </el-icon>
                        新增日报
                    </el-button>
                </div>


                <!-- 加载状态 -->
                <div v-if="loadingMore && reports.length === 0" class="loading-state" style="text-align: center; padding: 40px; color: #666;">
                    <el-icon class="is-loading" color="#409EFF" :size="24">
                        <Loading />
                    </el-icon>
                    <div style="margin-top: 8px;">正在加载日报数据...</div>
                </div>

                <!-- 错误状态 -->
                <div v-else-if="reports.length === 0 && !loadingMore" class="error-state" style="text-align: center; padding: 40px; color: #666;">
                    <el-icon color="#f56c6c" :size="48">
                        <Warning />
                    </el-icon>
                    <div style="margin-top: 16px; font-size: 16px; color: #f56c6c;">暂无日报数据</div>
                    <div style="margin-top: 8px; color: #999;">可能的原因：</div>
                    <div style="margin-top: 4px; color: #999;">1. 当前筛选条件下没有数据</div>
                    <div style="margin-top: 4px; color: #999;">2. 网络连接问题</div>
                    <div style="margin-top: 4px; color: #999;">3. 服务器暂时不可用</div>
                    <el-button @click="getDailyList(false)" type="primary" style="margin-top: 16px;">
                        <el-icon class="btn-icon">
                            <Refresh />
                        </el-icon>
                        重新加载
                    </el-button>
                </div>

                <template v-else-if="filteredReports.length > 0">
                    <div v-for="report in filteredReports" :key="report.ID" @click="loadReport(report.ID)"
                        class="report-item"
                        :class="{
                            'active-report': activeReportId === report.ID,
                            'draft-report': report.dailyType === 2,
                            'submitted-report': report.dailyType === 1
                        }">
                        <div class="report-header">
                            <div class="report-left-section">
                                <div class="report-author-section">
                                    <el-avatar :size="24" class="author-avatar">
                                        {{ report.userName ? report.userName.charAt(0) : 'U' }}
                                    </el-avatar>
                                    <span class="report-author">{{ report.userName }}{{ formatDailyDate(report.dailyDate) }}的日报</span>
                                </div>
                                <div class="report-date-section">
                                    <span class="report-date">{{ formatDateTime(report.createAt) }}</span>
                                </div>
                            </div>
                            <div class="report-right-section">
                                <div class="report-status-section">
                                    <el-tag
                                        :class="isReportRead(report) ? 'read-tag' : 'unread-tag'"
                                        size="small">
                                        <el-icon class="status-icon">
                                            <View v-if="isReportRead(report)" />
                                            <Clock v-else />
                                        </el-icon>
                                        {{ isReportRead(report) ? '已读' : '未读' }}
                                    </el-tag>
                                </div>
                            </div>
                        </div>
                        <div class="report-preview">
                            <div class="work-items-count">
                                <el-icon class="count-icon"><Document /></el-icon>
                                <span>工作项: {{ report.workItems ? report.workItems.length : 0 }}</span>
                            </div>
                            <div class="readers-count">
                                <el-icon class="count-icon"><User /></el-icon>
                                <span>已读: {{ report.itemDailyChecks ? report.itemDailyChecks.length : 0 }}</span>
                            </div>
                        </div>
                    </div>
                </template>
                <el-empty v-else description="暂无日报" :image-size="100" style="margin: 0px; padding: 0px;"></el-empty>
            </div>
        </div>

        <!-- 右侧内容区 -->
        <div class="main-content">
            <!-- 添加加载遮罩层 -->
            <div v-if="isLoadingReport || isInitializing" class="loading-overlay">
                <div class="loading-content">
                    <el-icon class="is-loading" color="#409EFF" :size="30">
                        <Loading />
                    </el-icon>
                    <span class="loading-text">{{ isInitializing ? '正在初始化...' : '加载中...' }}</span>
                </div>
            </div>
            <div class="report-card">
                <!-- 头部 -->
                <div class="detail-header">
                    <h1 class="report-title" :class="{ 'view-mode-title': isEdite }">
                        <template v-if="!isEdite">
                            {{ `${currentReport.author}新建日报` }}
                            <el-date-picker v-model="currentReport.dailyDate" type="date"
                                placeholder="选择日期" format="YYYY年MM月DD日" value-format="YYYY-MM-DD"
                                :default-value="new Date()" class="inline-date-picker"
                                :disabled-date="disableFutureDates"></el-date-picker>
                        </template>
                        <template v-else>
                            {{ `${currentReport.author}${formatDailyDate(currentReport.dailyDate)}报详情` }}
                        </template>
                        <el-tooltip
                            v-if="isEdite && currentReport.itemDailyChecks && currentReport.itemDailyChecks.length > 0"
                            effect="light">
                            <template #content>
                                <div style="max-width: 200px;">
                                    <div v-for="check in currentReport.itemDailyChecks" :key="check.ID"
                                        style="margin-bottom: 4px;">
                                        <el-tag size="Large" type="primary">{{ check.userName }}</el-tag>
                                        <span style="margin-left: 5px;font-size:12px;color:#909399">{{
                                            formatDateTime(check.checkDailyDate) }}</span>
                                    </div>
                                </div>
                            </template>
                            <el-tag size="Large" class="readers-tag">
                                <el-icon>
                                    <View />
                                </el-icon>
                                {{ currentReport.itemDailyChecks.length }}人已读
                            </el-tag>
                        </el-tooltip>
                    </h1>
                    <div class="header-right">
                        <!-- 新增搜索框 -->
                        <el-input v-model="searchKeyword" placeholder="搜索日报涉及内容" clearable class="search-input"
                            @clear="handleSearch" @keyup.enter="handleSearch">
                            <template #prefix>
                                <el-icon>
                                    <Search />
                                </el-icon>
                            </template>
                        </el-input>
                        <div class="action-buttons">
                            <el-button v-if="!isEdite" type="primary" @click="saveReport(2)" class="action-btn"
                                :loading="loading && dailyType === 2" :disabled="loading && dailyType !== 2">
                                <el-icon class="btn-icon">
                                    <DocumentAdd />
                                </el-icon>
                                保存草稿
                            </el-button>
                            <el-button v-if="!isEdite" type="success" @click="saveReport(1)" class="action-btn"
                                :loading="loading && dailyType === 1" :disabled="loading && dailyType !== 1">
                                <el-icon class="btn-icon">
                                    <Promotion />
                                </el-icon>
                                提交日报
                            </el-button>
                            <el-button v-if="activeReportId !== 0 && activeTab != 3 && isEdite && canEditReport" type="primary"
                                @click="editReport" class="action-btn">
                                <el-icon class="btn-icon">
                                    <Edit />
                                </el-icon>
                                编辑
                            </el-button>
                            <el-button @click="cancelEdit" class="action-btn" v-if="isReturn">
                                <el-icon class="btn-icon">
                                    <Close />
                                </el-icon>
                                {{ isViewMode ? '返回' : '取消' }}
                            </el-button>
                        </div>
                    </div>
                </div>

                <!-- 标题内已放置日期选择器，这里移除原日期区域 -->
                <!-- 工作内容 - 滚动区域 -->
                                    <div class="work-content-container" :class="{ 'new-report-mode': activeReportId === 0 }">
                    <div class="work-content-header">
                        <div class="work-content-header-left">
                            <el-icon class="content-icon">
                                <List />
                            </el-icon>
                            <h2 class="content-title">工作内容</h2>
                        </div>
                        <div class="work-content-header-right">
                            <!-- 移动端评论按钮 -->
                            <el-button 
                                v-if="isMobile() && activeReportId !== 0"
                                type="primary" 
                                size="small" 
                                @click="toggleCommentSection"
                                class="mobile-comment-btn"
                            >
                                <el-icon>
                                    <ChatLineRound />
                                </el-icon>
                                评论 {{ totalCommentCount }}
                            </el-button>
                        </div>
                    </div>

                    <!-- 可滚动的工作内容容器 -->
                    <div class="work-items-container">
                        <!-- 别人安排的工作 -->
                        <div class="work-item-section" :v-if="!isEdite || getWorkItemsByType(1).length > 0">
                            <div class="section-header">
                                <h3 class="section-title">别人安排的工作</h3>
                            </div>

                            <template v-if="getWorkItemsByType(1).length > 0">
                                <div class="work-item-grid">
                                    <div v-for="(item, index) in getWorkItemsByType(1)" :key="`assigned-${index}`"
                                        class="work-item">
                                    <template v-if="isEdite">
                                        <!-- 纯文本展示模式 -->
                                        <div class="plain-text-item">
                                            <span class="plain-text-content">
                                                【{{ getProjectName(item.itemId) }}】【{{ item.assigner.replace(/\n/g, '')
                                                }}】安排【{{
                                                    item.content.replace(/\n/g, '') }}】
                                                <template v-if="Number(item.timeSpent) > 0">耗时【{{ item.timeSpent }}h】</template>
                                                结果【{{ getResultText(item.result) }}】
                                            </span>
                                        </div>
                                    </template>
                                    <template v-else>
                                        <!-- 表单编辑模式 -->
                                        <el-form :model="item">
                                            <div class="flex-container">
                                                <div class="flex-item" style="width: 220px;float: left;">
                                                    <el-form-item label="项目名称" prop="itemId">
                                                        <el-select v-model="item.itemId" placeholder="请选择项目"
                                                            :disabled="true" clearable style="width: 120px;">
                                                            <el-option v-for="item in filteredProjects"
                                                                :key="item.value" :label="item.label"
                                                                :value="item.value" />
                                                        </el-select>
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item">
                                                    <el-form-item label="谁" prop="assigner">
                                                        <el-select v-model="item.assigner" :disabled="true"
                                                            placeholder="谁安排" clearable style="width: 120px;">
                                                            <el-option v-for="item in staffList" :key="item.name"
                                                                :label="item.name" :value="item.name" />
                                                        </el-select>
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item ultra-wide">
                                                    <el-form-item label="安排" prop="content">
                                                        <el-input v-model="item.content" :disabled="isEdite"
                                                            type="textarea" :rows="5"
                                                            placeholder="请输入具体工作内容..."
                                                            style="min-width: 150px; white-space: pre-wrap;" />
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item" style="width: 220px;float: left;">
                                                    <el-form-item label="耗时(h)" prop="timeSpent">
                                                        <el-input v-model="item.timeSpent" :disabled="isEdite"
                                                            style="width: 110px;" />
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item">
                                                    <el-form-item label="结果" prop="result">
                                                        <el-select v-model="item.result" :disabled="isEdite" clearable
                                                            style="width: 90px;">
                                                            <el-option label="未开始" :value="0" />
                                                            <el-option label="未完成" :value="1" />
                                                            <el-option label="完成" :value="2" />
                                                        </el-select>
                                                    </el-form-item>
                                                </div>
                                            </div>
                                        </el-form>
                                    </template>
                                    </div>
                                </div>
                            </template>
                            <el-empty v-else description="暂无别人安排的工作" :image-size="1"
                                style="margin: 0px;padding: 0px;" v-if="!isEdite" />
                        </div>

                        <!-- 安排别人的工作 -->
                        <div class="work-item-section" :v-if="!isEdite || getWorkItemsByType(2).length > 0">
                            <div class="section-header">
                                <h3 class="section-title">安排别人的工作</h3>
                            </div>

                            <template v-if="getWorkItemsByType(2).length > 0">
                                <div class="work-item-grid">
                                    <div v-for="item in getWorkItemsByType(2)" :key="item.cardId"
                                        class="work-item">
                                    <template v-if="isEdite">
                                        <!-- 纯文本展示模式 -->
                                        <div class="plain-text-item">
                                            <span class="plain-text-content">
                                                【{{ getProjectName(item.itemId) }}】安排【{{ item.assigner.replace(/\n/g,
                                                    '') }}】完成【{{
                                                    item.content.replace(/\n/g, '') }}】
                                                结果【{{ getResultText(item.result) }}】
                                                <template v-if="item.assignerResult !== undefined">
                                                    ，安排人结果【{{ getResultText(item.assignerResult) }}】
                                                    <el-tag v-if="item.assignerResult !== item.result" type="danger" size="small" style="margin-left:6px;">结果不一致</el-tag>
                                                </template>
                                            </span>
                                        </div>
                                    </template>
                                    <template v-else>
                                        <!-- 表单编辑模式 -->
                                        <el-form :model="item">
                                            <div class="flex-container">
                                                <div class="flex-item" style="width: 220px;float: left;">
                                                    <el-form-item label="项目名称" prop="itemId">
                                                        <el-select v-model="item.itemId" placeholder="请选择项目"
                                                            :disabled="true" clearable style="width: 120px;">
                                                            <el-option v-for="item in filteredProjects"
                                                                :key="item.value" :label="item.label"
                                                                :value="item.value" />
                                                        </el-select>
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item">
                                                    <el-form-item label="安排" prop="assigner">
                                                        <el-select v-model="item.assigner" :disabled="true"
                                                            placeholder="安排谁" clearable style="width: 120px;">
                                                            <el-option v-for="item in staffList" :key="item.name"
                                                                :label="item.name" :value="item.name" />
                                                        </el-select>
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item ultra-wide">
                                                    <el-form-item label="内容" prop="content">
                                                        <el-input v-model="item.content" :disabled="isEdite"
                                                            type="textarea" :rows="5"
                                                            placeholder="请输入具体工作内容..." style="white-space: pre-wrap;" />
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item" style="width: 200px;float: left;">
                                                    <el-form-item label="结果" prop="result">
                                                        <el-select v-model="item.result" :disabled="isEdite"
                                                            class="result-select"
                                                            :class="getResultTagClass(item.result)"
                                                            style="width: auto; min-width: 96px;">
                                                            <template #prefix>
                                                                <el-tag :type="item.result === 2 ? 'success' : (item.result === 1 ? 'warning' : 'info')" size="small">
                                                                    {{ getResultText(item.result) }}
                                                                </el-tag>
                                                            </template>
                                                            <el-option :value="0" label="未开始">
                                                                <el-tag type="info" size="small">未开始</el-tag>
                                                            </el-option>
                                                            <el-option :value="1" label="未完成">
                                                                <el-tag type="warning" size="small">未完成</el-tag>
                                                            </el-option>
                                                            <el-option :value="2" label="完成">
                                                                <el-tag type="success" size="small">完成</el-tag>
                                                            </el-option>
                                                        </el-select>
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item" v-if="item.assignerResult !== undefined">
                                                    <el-form-item label="安排人结果">
                                                        <el-tag :type="item.assignerResult === 2 ? 'success' : (item.assignerResult === 1 ? 'warning' : 'info')">
                                                            {{ getResultText(item.assignerResult) }}
                                                        </el-tag>
                                                    </el-form-item>
                                                </div>
                                            </div>
                                        </el-form>
                                    </template>
                                    </div>
                                </div>
                            </template>
                            <el-empty v-else description="暂无安排别人的工作" :image-size="1" style="margin: 0px;padding: 0px;" v-if="!isEdite" />
                        </div>

                        <!-- 其他工作内容 -->
                        <div class="work-item-section" :v-if="!isEdite || getWorkItemsByType(3).length > 0">
                            <div class="section-header">
                                <h3 class="section-title">其他工作内容（未在管理平台创建的任务）</h3>
                                <el-button v-if="!isEdite" type="primary" @click="addWorkItem(3)" size="small"
                                    class="add-btn">
                                    <el-icon class="btn-icon">
                                        <Plus />
                                    </el-icon>
                                    添加其他工作
                                </el-button>
                            </div>
                            <template v-if="getWorkItemsByType(3).length > 0">
                                <div class="work-item-grid">
                                    <div v-for="(item, index) in getWorkItemsByType(3)" :key="`other-${index}`"
                                        class="work-item">
                                    <template v-if="isEdite">
                                        <!-- 纯文本展示模式 -->
                                        <div class="plain-text-item">
                                            <span class="plain-text-content">
                                                【{{ getProjectName(item.itemId) }}】【{{ item.assigner.replace(/\n/g, '')
                                                }}】安排【{{
                                                    item.content.replace(/\n/g, '') }}】
                                                <template v-if="Number(item.timeSpent) > 0">耗时【{{ item.timeSpent }}h】</template>
                                                结果【{{ getResultText(item.result) }}】
                                            </span>
                                        </div>
                                    </template>
                                    <template v-else>
                                        <!-- 表单编辑模式 -->
                                        <el-form :model="item" :ref="(el: any) => { if (el) otherForms[index] = el }">
                                            <div class="flex-container">
                                                <div class="flex-item" style="width: 220px;float: left;">
                                                    <el-form-item label="项目名称" prop="itemId">
                                                        <el-select v-model="item.itemId" filterable placeholder="请选择项目"
                                                            :disabled="isEdite" clearable style="width: 120px;">
                                                            <el-option v-for="item in filteredProjects"
                                                                :key="item.value" :label="item.label"
                                                                :value="item.value" />
                                                        </el-select>
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item">
                                                    <el-form-item label="" prop="assigner">
                                                        <el-select v-model="item.assigner" filterable allow-create
                                                            :disabled="isEdite" default-first-option placeholder="谁安排"
                                                            clearable style="width: 120px;">
                                                            <el-option v-for="item in staffList" :key="item.name"
                                                                :label="item.name" :value="item.name" />
                                                        </el-select>
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item ultra-wide">
                                                    <el-form-item label="内容" prop="content">
                                                        <el-input v-model="item.content" :disabled="isEdite"
                                                            type="textarea" :rows="5"
                                                            placeholder="请输入具体工作内容..."
                                                            style="min-width: 150px; white-space: pre-wrap;" />
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item" style="width: 145px;float: left;">
                                                    <el-form-item label="耗时(h)" prop="timeSpent">
                                                        <el-input v-model="item.timeSpent" :disabled="isEdite"
                                                            style="width: 80px;" />
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item" style="width: 150px;float: left;">
                                                    <el-form-item label="结果" prop="result">
                                                        <el-select v-model="item.result" :disabled="isEdite" clearable
                                                            style="width: 90px;">
                                                            <el-option label="未开始" :value="0" />
                                                            <el-option label="未完成" :value="1" />
                                                            <el-option label="完成" :value="2" />
                                                        </el-select>
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-del" v-if="!isEdite" style="float: right;">
                                                    <el-button type="danger" size="small"
                                                        @click="removeWorkItem(3, index)" class="action-btn">
                                                        <el-icon>
                                                            <Delete />
                                                        </el-icon>
                                                    </el-button>
                                                </div>
                                            </div>
                                        </el-form>
                                    </template>
                                    </div>
                                </div>
                            </template>
                            <el-empty v-else description="暂无其他工作" :image-size="1" style="margin: 0px;padding: 0px;" v-if="!isEdite" />
                        </div>

                        <!-- 市场部沟通 -->
                        <div class="work-item-section" :v-if="!isEdite || getWorkItemsByType(4).length > 0">
                            <div class="section-header">
                                <h3 class="section-title">每周与市场部沟通事宜（项目经理填写）</h3>
                                <el-button v-if="!isEdite" type="primary" @click="addWorkItem(4)" size="small"
                                    class="add-btn">
                                    <el-icon class="btn-icon">
                                        <Plus />
                                    </el-icon>
                                    添加市场部沟通
                                </el-button>
                            </div>
                            <template v-if="getWorkItemsByType(4).length > 0">
                                <div class="work-item-grid">
                                    <div v-for="(item, index) in getWorkItemsByType(4)" :key="`market-${index}`"
                                        class="work-item">
                                    <template v-if="isEdite">
                                        <!-- 纯文本展示模式 -->
                                        <div class="plain-text-item">
                                            <span class="plain-text-content">
                                                【{{ getProjectName(item.itemId) }}】与【{{ item.assigner.replace(/\n/g, '')
                                                }}】沟通【{{
                                                    item.content.replace(/\n/g, '') }}】
                                                结果【{{ getResultText(item.result) }}】
                                            </span>
                                        </div>
                                    </template>
                                    <template v-else>
                                        <!-- 表单编辑模式 -->
                                        <el-form :model="item" :ref="(el: any) => { if (el) marketForms[index] = el }">
                                            <div class="flex-container">
                                                <div class="flex-item" style="width: 220px;float: left;">
                                                    <el-form-item label="项目名称" prop="itemId">
                                                        <el-select v-model="item.itemId" filterable placeholder="请选择项目"
                                                            :disabled="isEdite" clearable style="width: 120px;">
                                                            <el-option v-for="item in filteredProjects"
                                                                :key="item.value" :label="item.label"
                                                                :value="item.value" />
                                                        </el-select>
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item">
                                                    <el-form-item label="市场人员" prop="assigner">
                                                        <el-select v-model="item.assigner" filterable allow-create
                                                            :disabled="isEdite" default-first-option placeholder="市场人员"
                                                            clearable style="width: 120px;">
                                                            <el-option v-for="item in staffList" :key="item.name"
                                                                :label="item.name" :value="item.name" />
                                                        </el-select>
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item ultra-wide">
                                                    <el-form-item label="内容" prop="content">
                                                        <el-input v-model="item.content" :disabled="isEdite"
                                                            type="textarea" :rows="5"
                                                            placeholder="请输入沟通详情..."
                                                            style="min-width: 150px; white-space: pre-wrap;" />
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item" style="width: 220px;float: left;">
                                                    <el-form-item label="结果" prop="result">
                                                        <el-select v-model="item.result" :disabled="isEdite" clearable
                                                            style="width: 90px;">
                                                            <el-option label="未开始" :value="0" />
                                                            <el-option label="未完成" :value="1" />
                                                            <el-option label="完成" :value="2" />
                                                        </el-select>
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-del" v-if="!isEdite" style="float: right;">
                                                    <el-button type="danger" size="small"
                                                        @click="removeWorkItem(4, index)" class="action-btn">
                                                        <el-icon>
                                                            <Delete />
                                                        </el-icon>
                                                    </el-button>
                                                </div>
                                            </div>
                                        </el-form>
                                    </template>
                                    </div>
                                </div>
                            </template>
                            <el-empty v-else description="暂无市场部沟通" :image-size="1" style="margin: 0px;padding: 0px;" v-if="!isEdite" />
                        </div>

                        <!-- 标注内容 -->
                        <div class="work-item-section" :v-if="!isEdite || getWorkItemsByType(5).length > 0">
                            <div class="section-header">
                                <h3 class="section-title">标注内容：和甲方发生的无法报工作量的事宜（技术负责人，项目经理填写）</h3>
                                <el-button v-if="!isEdite" type="primary" @click="addWorkItem(5)" size="small"
                                    class="add-btn">
                                    <el-icon class="btn-icon">
                                        <Plus />
                                    </el-icon>
                                    添加标注内容
                                </el-button>
                            </div>
                            <template v-if="getWorkItemsByType(5).length > 0">
                                <div class="work-item-grid">
                                    <div v-for="(item, index) in getWorkItemsByType(5)" :key="`annotation-${index}`"
                                        class="work-item">
                                    <template v-if="isEdite">
                                        <!-- 纯文本展示模式 -->
                                        <div class="plain-text-item">
                                            <span class="plain-text-content">
                                                【{{ getProjectName(item.itemId) }}】与【{{ item.assigner.replace(/\n/g, '')
                                                }}】处理【{{
                                                    item.content.replace(/\n/g, '') }}】
                                                结果【{{ getResultText(item.result) }}】
                                            </span>
                                        </div>
                                    </template>
                                    <template v-else>
                                        <!-- 表单编辑模式 -->
                                        <el-form :model="item"
                                            :ref="(el: any) => { if (el) annotationForms[index] = el }">
                                            <div class="flex-container">
                                                <div class="flex-item" style="width: 200px;float: left;">
                                                    <el-form-item label="项目名称" prop="itemId">
                                                        <el-select v-model="item.itemId" filterable placeholder="请选择项目"
                                                            :disabled="isEdite" clearable style="width: 120px;">
                                                            <el-option v-for="item in filteredProjects"
                                                                :key="item.value" :label="item.label"
                                                                :value="item.value" />
                                                        </el-select>
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item">
                                                    <el-form-item label="甲方人员" prop="assigner">
                                                        <el-input v-model="item.assigner" :disabled="isEdite"
                                                            placeholder="请输入甲方人员姓名" clearable style="width: 150px;" />
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item ultra-wide">
                                                    <el-form-item label="内容" prop="content">
                                                        <el-input v-model="item.content" :disabled="isEdite"
                                                            type="textarea" :rows="5"
                                                            placeholder="请输入无法报工作量的具体事宜..."
                                                            style="min-width: 150px; white-space: pre-wrap;" />
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-item" style="width: 220px;float: left;">
                                                    <el-form-item label="结果" prop="result">
                                                        <el-select v-model="item.result" :disabled="isEdite" clearable
                                                            style="width: 90px;">
                                                            <el-option label="未开始" :value="0" />
                                                            <el-option label="未完成" :value="1" />
                                                            <el-option label="完成" :value="2" />
                                                        </el-select>
                                                    </el-form-item>
                                                </div>
                                                <div class="flex-del" v-if="!isEdite" style="float: right;">
                                                    <el-button type="danger" size="small"
                                                        @click="removeWorkItem(5, index)" class="action-btn">
                                                        <el-icon>
                                                            <Delete />
                                                        </el-icon>
                                                    </el-button>
                                                </div>
                                            </div>
                                        </el-form>
                                    </template>
                                    </div>
                                </div>
                            </template>
                            <el-empty v-else description="暂无标注内容" :image-size="1" style="margin: 0px;padding: 0px;" v-if="!isEdite" />
                        </div>
                    </div>

                    <!-- 评论区域（输入框在列表上方） -->
                    <div class="comment-section" v-if="activeReportId !== 0">
                        <div class="comment-header">
                            <div class="comment-header-left">
                                <el-icon class="content-icon">
                                    <ChatLineRound />
                                </el-icon>
                                <h2 class="content-title">评论</h2>
                            </div>
                            <div class="comment-header-right">
                                <!-- 评论按钮 -->
                                <el-button 
                                    type="primary" 
                                    size="small" 
                                    @click="toggleCommentSection"
                                    class="comment-toggle-btn"
                                >
                                    <el-icon>
                                        <ChatLineRound />
                                    </el-icon>
                                    评论
                                    <el-tag size="small" class="comment-count-badge">{{ totalCommentCount }}</el-tag>
                                </el-button>
                            </div>
                        </div>

                        <!-- 评论输入框 -->
                        <div class="comment-input" v-show="showCommentSection">
                            <div v-if="replyingTo" class="reply-info">
                                正在回复 @{{ replyingToAuthor }}
                                <el-button type="text" @click="cancelReply">取消</el-button>
                            </div>
                            <el-input
                                v-model="newComment"
                                type="textarea"
                                :rows="2"
                                placeholder="请输入评论内容... 支持 @ 提及"
                                resize="none"
                                maxlength="200"
                                show-word-limit
                                @keyup.enter="submitComment"
                                @input="handleCommentInput"
                                @focus="handleInputFocus"
                                @keydown="handleKeyDown"
                            />

                            
                            <div v-if="showMentionList" class="mention-list-container">
                                <div class="mention-list">
                                    <div class="mention-header">
                                        <el-icon class="mention-icon"><User /></el-icon>
                                        <span class="mention-title">选择要@的人员</span>
                                        <span class="mention-count" v-if="filteredMentionUsers.length > 0">{{ filteredMentionUsers.length }}人</span>
                                    </div>
                                    <div class="mention-items" v-if="filteredMentionUsers.length > 0">
                                        <div
                                            v-for="user in filteredMentionUsers"
                                            :key="user.id"
                                            class="mention-item"
                                            @click="selectMentionUser(user)"
                                        >
                                            <div class="mention-avatar">
                                                <el-avatar :size="32" :src="user.avatar" class="user-avatar">
                                                    {{ user.name.charAt(0) }}
                                                </el-avatar>
                                            </div>
                                            <div class="mention-info">
                                                <div class="mention-name">
                                                    <span v-html="highlightSearchText(user.name, mentionSearchText)"></span>
                                                </div>
                                            </div>
                                            <div class="mention-action">
                                                <el-icon class="action-icon"><Plus /></el-icon>
                                            </div>
                                        </div>
                                    </div>
                                    <div v-else class="mention-no-results">
                                        <el-icon class="no-results-icon"><Search /></el-icon>
                                        <span class="no-results-text">未找到匹配的人员</span>
                                        <div class="no-results-tip">尝试输入姓名或部门关键词</div>
                                    </div>
                                </div>
                            </div>

                            <div class="comment-actions">
                                <el-button 
                                    type="primary" 
                                    size="small" 
                                    @click="submitComment" 
                                    :disabled="!newComment.trim() || isSubmittingComment"
                                    :loading="isSubmittingComment"
                                >
                                    {{ isSubmittingComment ? '提交中...' : '提交评论' }}
                                </el-button>
                            </div>
                        </div>

                        <!-- 评论列表 -->
                        <div class="comment-list" v-show="showCommentSection">
                            <template v-if="commentsLoading">
                                <div v-for="i in 3" :key="i" class="comment-item-skeleton">
                                    <el-skeleton-item variant="circle" style="width: 28px; height: 28px" />
                                    <div style="flex: 1; margin-left: 10px;">
                                        <el-skeleton-item variant="text" style="width: 30%" />
                                        <el-skeleton-item variant="text" style="width: 60%; margin-top: 6px;" />
                                    </div>
                                </div>
                            </template>
                            <template v-else>
                                <CommentItem
                                    v-for="comment in comments"
                                    :key="comment.ID"
                                    :comment="comment"
                                    :replying-to="replyingTo"
                                    :replying-to-author="replyingToAuthor"
                                    @reply-click="handleReplyClick"
                                />
                                <el-empty v-if="comments.length === 0" description="暂无评论" :image-size="60" />
                            </template>
                        </div>
                    </div>

                    
                </div>
            </div>
        </div>
    </div>
    
    <!-- 移动端评论模态框 -->
    <MobileCommentModal
        v-model="showMobileCommentModal"
        :report-id="activeReportId || 0"
        :current-user="userStore.userInfo"
        @comment-submitted="handleMobileCommentSubmitted"
    />
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch, onUnmounted, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import useUserStore from '@/store/modules/user'
import {
    Plus,
    DocumentAdd,
    Promotion,
    Edit,
    Close,
    List,
    Delete,
    Search,
    View,
    Clock,
    User,
    Document,
    Filter,
    ArrowDown,
    Warning,
    ChatLineRound,
    
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import {
    GetItemList,
    GetDailyUserListByDepartment,
    CreateDaily,
    GetDailyList,
    GetDailyById,
    GetMyDailyOneToMany,
    GetToComments,
    ToComments,
    
} from "@/api/newDemands/index";
import CommentItem from '@/views/daily/daily/CommentItem.vue'
import MobileCommentModal from '@/components/requirement/MobileCommentModal.vue'
import type { Comment } from '@/views/daily/daily/CommentItem.vue'


const userStore = useUserStore()
const loading = ref(false); // 新增 loading 状态

const loadingMore = ref(false)
const noMoreData = ref(false)
const pageSize = 20 // 每页加载数量
const currentPage = ref(1)

interface WorkItem {
    workType: 1 | 2 | 3 | 4 | 5
    itemId: number
    cardId?: number
    assigner: string
    content: string
    timeSpent: string
    result: 0 | 1 | 2  // 0: 未开始, 1: 未完成, 2: 完成
    assignerResult?: 0 | 1 | 2 // 安排人结果（仅用于 workType=2）
}

interface ItemDailyCheck {
    ID: number
    userName: string
    userUUID: string
    checkDailyId: string
    checkDailyDate: string
    createAt: string
    UpdatedAt: string
}

interface DailyReport {
    ID: number
    cardId?: number
    status: 1 | 2
    author: string
    viewed?: boolean
    workItems: WorkItem[]
    itemDailyChecks: ItemDailyCheck[]
    summary: string
    dailyType?: number
    userName?: string
    dailyDate: string
    createAt: string
}

// 状态管理
const activeTab = ref<1 | 2 | 3>(2)
const activeReportId = ref<number>(0)
const isViewMode = ref(false)
const isNewReport = ref(false)
const isReturn = ref(false)
const isEdite = ref(false);
const selectedMonth = ref<string>(`${new Date().getFullYear()}-${(new Date().getMonth() + 1).toString().padStart(2, '0')}`)
const selectedAuthor = ref<string>('all')
const authorLoading = ref(false)
// const dateForm = ref<FormInstance>()



// 评论功能已彻底移除

// 简化后仍需键盘监听的其它逻辑可在此扩展
const handleKeyDown = (e: KeyboardEvent) => {
    console.log('handleKeyDown triggered:', e.key)
    // 处理@提及功能 - 对所有字符都进行过滤更新
    if (showMentionList.value || e.key === '@') {
        // 延迟执行，确保v-model更新完成
        setTimeout(() => {
            const text = newComment.value
            const cursorPos = (e.target as HTMLTextAreaElement)?.selectionStart || 0
            const lastAtPos = text.lastIndexOf('@', cursorPos - 1)

            // 空格键：若正在显示@列表，则立即关闭
            if ((e.key === ' ' || text.charAt(cursorPos - 1) === ' ') && showMentionList.value) {
                showMentionList.value = false
                mentionStartIndex.value = -1
                mentionSearchText.value = ''
                filteredMentionUsers.value = []
                return
            }

            // 如果原始触发的 @ 已不存在，则直接关闭
            if (showMentionList.value && mentionStartIndex.value >= 0) {
                const stillHasOriginAt = text.length > mentionStartIndex.value && text.charAt(mentionStartIndex.value) === '@'
                if (!stillHasOriginAt) {
                    console.log('Origin @ removed (keydown) -> close mention list')
                    showMentionList.value = false
                    mentionStartIndex.value = -1
                    mentionSearchText.value = ''
                    filteredMentionUsers.value = []
                    return
                }
            }
            
            if (lastAtPos >= 0) {
                mentionStartIndex.value = lastAtPos
                mentionSearchText.value = text.substring(lastAtPos + 1, cursorPos)
                showMentionList.value = true
                
                // 使用智能搜索算法
                filteredMentionUsers.value = staffList.value.filter(user => {
                    const searchText = mentionSearchText.value.toLowerCase()
                    const userName = user.name.toLowerCase()
                    const userDept = (user.department || '').toLowerCase()
                    
                    return userName.includes(searchText) || userDept.includes(searchText)
                }) as unknown as Staff[]
                
                // 按匹配度排序
                filteredMentionUsers.value.sort((a, b) => {
                    const searchText = mentionSearchText.value.toLowerCase()
                    const aName = a.name.toLowerCase()
                    const bName = b.name.toLowerCase()
                    
                    if (aName === searchText && bName !== searchText) return -1
                    if (bName === searchText && aName !== searchText) return 1
                    
                    const aStartsWith = aName.startsWith(searchText)
                    const bStartsWith = bName.startsWith(searchText)
                    if (aStartsWith && !bStartsWith) return -1
                    if (bStartsWith && !aStartsWith) return 1
                    
                    return aName.length - bName.length
                })
            } else {
                showMentionList.value = false
            }
        }, 10)
    }
    
    // 处理删除键，只要删除就关闭人员列表；或删除后原始 @ 不存在
    if (e.key === 'Backspace' || e.key === 'Delete') {
        console.log('Delete key pressed - maybe close mention list')
        setTimeout(() => {
            const text = newComment.value
            const originAtExists = mentionStartIndex.value >= 0 && text.length > mentionStartIndex.value && text.charAt(mentionStartIndex.value) === '@'
            if (!originAtExists && showMentionList.value) {
                console.log('Close list because origin @ removed after delete')
                showMentionList.value = false
                mentionStartIndex.value = -1
                mentionSearchText.value = ''
                filteredMentionUsers.value = []
            }
        }, 10)
    }
}

const searchKeyword = ref('')
const handleSearch = () => {
    getDailyList();
}

// 评论功能已移除
// 评论逻辑已移除

// 评论组件已移除

// 定义固定部门列表
const departments = [
    { value: '研发部', label: '研发部' },
    { value: '测试部', label: '测试部' },
    { value: '运维部', label: '运维部' },
    { value: '项目部', label: '项目部' }
]

// 部门筛选状态
const selectedDepartment = ref<string>('all')
// 部门筛选方法
const filterByDepartment = () => {
    getAllUsers(selectedDepartment.value);
    getDailyList();
}

// 数据存储
const reports = ref<DailyReport[]>([])
const filteredProjects = ref<{ value: number, label: string }[]>([])

// 获取所有项目
const getItemList = async () => {
    try {
        const { data } = await GetItemList()
        if (data.code == 200) {
            filteredProjects.value = data.data.map((item: any) => ({
                value: item.ID,
                label: item.itemName,
            }))
        } else {
            console.error('获取项目列表失败:', data.msg);
            ElMessage.error(data.msg)
            filteredProjects.value = []
        }
    } catch (error: any) {
        console.error('获取项目列表异常:', error);
        ElMessage.error('获取项目列表失败')
        filteredProjects.value = []
    }
}

// 获取所有用户
interface Staff {
    id: string
    name: string
    department: string // 部门名称
    avatar?: string // 头像URL
}
const staffList = ref<Staff[]>([])
const getAllUsers = async (department?: string) => {
    try {
        const dept = department || selectedDepartment.value;
        const { data } = await GetDailyUserListByDepartment(dept)
        if (data.code == 200) {
            staffList.value = data.data.map((item: any) => ({
                id: item.uuid,
                name: item.userName,
                department: item.department || '未知部门',
                avatar: item.avatar || item.headerImg || ''
            }))
        } else {
            console.error('获取用户列表失败:', data.msg);
            ElMessage.error(data.msg)
            staffList.value = []
        }
    } catch (error: any) {
        console.error('获取用户列表异常:', error);
        ElMessage.error('获取用户列表失败')
        staffList.value = []
    }
}

// 当前编辑的日报
const currentReport = ref<DailyReport>({
    ID: 0,
    dailyType: 1,
    dailyDate: new Date().toISOString().split('T')[0],
    createAt: new Date().toISOString().split('T')[0],
    status: 2,
    author: '',
    workItems: [],
    itemDailyChecks: [],
    summary: ''
})

// 判断日报是否已读的方法
const isReportRead = (report: DailyReport): boolean => {
    // 添加调试信息

    // 如果当前用户是日报作者，则认为是已读
    if (report.userName === userStore.userInfo.nickName) {
        return true;
    }

    // 检查是否有已读记录，并且当前用户在其中
    if (report.itemDailyChecks && report.itemDailyChecks.length > 0) {
        const isRead = report.itemDailyChecks.some(check =>
            check.userName === userStore.userInfo.nickName
        );
        return isRead;
    }

    return false;
};

// 修改filteredReports计算属性
const filteredReports = computed(() => {
    return reports.value || [];
});

// 判断是否可以编辑日报的计算属性
const canEditReport = computed(() => {
    if (!currentReport.value.createAt) return false;

    const createDate = new Date(currentReport.value.createAt);
    createDate.setHours(0, 0, 0, 0);
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const minDate = new Date(today);
    minDate.setDate(minDate.getDate() - 2);

    // 草稿箱中的日报：可以编辑，不限制天数
    if (activeTab.value === 1 || currentReport.value.dailyType === 2) {
        return true;
    }

    // 已提交中的日报：可以编辑，但限制只能编辑创建后两天内的日志
    if (activeTab.value === 2 || currentReport.value.dailyType === 1) {
        return createDate.getTime() >= minDate.getTime() && createDate.getTime() <= today.getTime();
    }

    // 全部日报中：根据日报类型判断
    if (activeTab.value === 3) {
        if (currentReport.value.dailyType === 2) { // 草稿：不限制天数
            return true;
        } else if (currentReport.value.dailyType === 1) { // 已提交：限制天数
            return createDate.getTime() >= minDate.getTime() && createDate.getTime() <= today.getTime();
        }
    }

    return false;
});

// 监听activeTab变化
watch([activeTab], () => {
    getDailyList();
});

// 监听筛选条件变化
watch([selectedMonth, selectedAuthor, selectedDepartment, searchKeyword], () => {
    getDailyList();
}, { deep: true });

// 按类型获取工作项
const getWorkItemsByType = (type: number): WorkItem[] => {
    if (!currentReport.value.workItems || !Array.isArray(currentReport.value.workItems)) {
        return []
    }
    return currentReport.value.workItems.filter(item => item.workType === type)
}

// 添加工作项
const addWorkItem = (workType: 1 | 2 | 3 | 4 | 5) => {
    const newItem = {
        workType,
        itemId: 23,
        assigner: '',
        content: '',
        timeSpent: "0",
        result: 0  // 默认未开始，使用数值以与下拉选项匹配
    }

    if (!currentReport.value.workItems) {
        currentReport.value.workItems = []
    }

    currentReport.value.workItems.push(JSON.parse(JSON.stringify(newItem)))
}

// 删除工作项
const removeWorkItem = (type: number, index: number) => {
    const itemsOfType = currentReport.value.workItems.filter(item => item.workType === type)
    if (itemsOfType[index]) {
        const globalIndex = currentReport.value.workItems.indexOf(itemsOfType[index])
        if (globalIndex !== -1) {
            currentReport.value.workItems.splice(globalIndex, 1)
            ElMessage.success('工作项已删除')
        }
    }
}

// 格式化日期为YYYY-MM-DD
const formatDate = (dateString: string) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}年${(date.getMonth() + 1).toString().padStart(2, '0')}月${date.getDate().toString().padStart(2, '0')}日`;
};

// 格式化时间为HH:mm
// 保留但不导出使用，避免未使用警告，可按需启用
// const formatTime = (dateString: string) => {
//     if (!dateString) return '';
//     const date = new Date(dateString);
//     const hours = date.getHours().toString().padStart(2, '0');
//     const minutes = date.getMinutes().toString().padStart(2, '0');
//     return `${hours}:${minutes}`;
// };

// 格式化日期时间为YYYY-MM-DD HH:mm
const formatDateTime = (dateString: string) => {
    if (!dateString) {
        return '';
    }

    try {
        const date = new Date(dateString);

        // 检查日期是否有效
        if (isNaN(date.getTime())) {
            return dateString;
        }

        // 服务器返回的是UTC时间，需要转换为本地时间（中国时区UTC+8）
        // 手动减去8小时来修正时区问题
        const localDate = new Date(date.getTime() - 8 * 60 * 60 * 1000);

        // 格式化为 YYYY-MM-DD HH:mm 格式
        const year = localDate.getFullYear();
        const month = (localDate.getMonth() + 1).toString().padStart(2, '0');
        const day = localDate.getDate().toString().padStart(2, '0');
        const hours = localDate.getHours().toString().padStart(2, '0');
        const minutes = localDate.getMinutes().toString().padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (error) {
        console.error('formatDateTime: 时间格式化错误:', error);
        return dateString; // 出错时返回原始字符串
    }
};

// 格式化当前时间为本地时间字符串
const formatCurrentTime = () => {
    const now = new Date();
    return now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    }).replace(/\//g, '-');
};

const disableFutureDates = (time: Date) => {
    const today = new Date()
    today.setHours(0, 0, 0, 0) // 清除时间部分，只比较日期
    return time.getTime() > today.getTime()
}

// 根据名字筛选
const filterAuthors = (query: string) => {
    selectedAuthor.value = query
    getDailyList();
}

// 根据月份筛选
const filterMonth = () => {
    getDailyList();
}

// 初始化创建内容
const createNewReport = async () => {
    isInitializing.value = true;
    try {
        const today = new Date().toISOString().split('T')[0]
        currentReport.value = {
            ID: 0,
            dailyType: 2,
            dailyDate: today,
            createAt: today,
            status: 2,
            author: '',
            workItems: [],
            itemDailyChecks: [],
            summary: ''
        }
        activeReportId.value = 0;
        isNewReport.value = true;
        isEdite.value = false;
        isViewMode.value = false;
        // 新增日报时隐藏评论区域
        showCommentSection.value = false;
        // 加载可选未完成安排需求
        await getMyDailyOneToMany();
    } finally {
        isInitializing.value = false;
    }
}

// 加载日报详情
const loadReport = async (id: number) => {
    isLoadingReport.value = true;
    try {
        const { data } = await GetDailyById(id);
        if (data.code == 200) {
            currentReport.value.author = data.data.userName
            currentReport.value.dailyType = data.data.dailyType
            currentReport.value.dailyDate = data.data.dailyDate
            // 保留原有的已读记录
            currentReport.value.itemDailyChecks = data.data.itemDailyChecks || []
            currentReport.value.workItems = (data.data.workItems || []).map((w:any)=>({
                ...w,
                result: typeof w.result === 'string' ? Number(w.result) : (w.result ?? 0)
            }))

            // 更新列表中的对应日报
            const reportIndex = reports.value.findIndex(r => r.ID === id)
            if (reportIndex !== -1) {
                reports.value[reportIndex].itemDailyChecks = data.data.itemDailyChecks || []
            }

            // 如果当前用户不是日报作者，且还没有标记为已读，则标记为已读
            if (data.data.userName !== userStore.userInfo.nickName &&
                !isReportRead(currentReport.value)) {
                // 添加当前用户到已读列表
                const newCheck = {
                    ID: Date.now(), // 临时ID
                    userName: userStore.userInfo.nickName,
                    userUUID: userStore.userInfo.uuid,
                    checkDailyId: String(data.data.ID),
                    checkDailyDate: formatCurrentTime(),
                    createAt: formatCurrentTime(),
                    UpdatedAt: formatCurrentTime()
                };

                currentReport.value.itemDailyChecks.push(newCheck);

                // 更新列表中的对应日报
                if (reportIndex !== -1) {
                    reports.value[reportIndex].itemDailyChecks.push(newCheck);
                }
            }

            activeReportId.value = id
            isNewReport.value = false
            isViewMode.value = true
            isEdite.value = true;

            // 加载评论
            await getComments();

            // 等待DOM更新后重置滚动位置
            await nextTick();
            const workItemsContainer = document.querySelector('.work-items-container') as HTMLElement;
            if (workItemsContainer) {
                workItemsContainer.scrollTop = 0;
            }
        } else {
            ElMessage.error(data.msg)
        }
    } catch (error: any) {
        if (error.response) {
            // 服务器返回了错误响应
            const status = error.response.status;
            if (status === 404) {
                ElMessage.error('日报不存在或已被删除');
            } else if (status === 401) {
                ElMessage.error('无权限查看该日报');
            } else if (status === 500) {
                ElMessage.error('服务器错误，请稍后再试');
            } else {
                ElMessage.error(`加载日报失败: ${error.response.data?.msg || error.message}`);
            }
        } else if ((error as any).request) {
            // 请求已发出但没有收到响应
            ElMessage.error('网络错误，请检查网络连接');
        } else {
            // 其他错误
            ElMessage.error(`加载日报失败: ${(error as any).message}`);
        }
        console.error('加载日报错误详情:', error);
    } finally {
        isLoadingReport.value = false;
    }
};

// 编辑日报
const editReport = () => {
    // 检查是否可以编辑
    if (!canEditReport.value) {
        if (currentReport.value.dailyType === 1) {
            ElMessage.warning('已提交的日报只能编辑创建后两天内的日志')
        } else {
            ElMessage.warning('无法编辑该日报')
        }
        return
    }

    getMyDailyOneToMany();
    isEdite.value = false
    isViewMode.value = false
    isReturn.value = true
}

// 取消编辑
const cancelEdit = () => {
    isReturn.value = false
    if (isNewReport.value) {
        createNewReport()
    } else if (activeReportId.value) {
        loadReport(activeReportId.value)
    }
    isViewMode.value = true
}

// 在 setup 中定义 ref
const otherForms = ref<FormInstance[]>([])
const marketForms = ref<FormInstance[]>([])
const annotationForms = ref<FormInstance[]>([])

// 修改后的验证方法
const validateAllForms = async () => {
    // 验证日期
    if (!currentReport.value.dailyDate) {
        ElMessage.warning('请填写日报日期')
        return false
    }

    // 验证工作项
    if (!currentReport.value.workItems || currentReport.value.workItems.length === 0) {
        ElMessage.warning('请至少添加一个工作项')
        return false
    }

    // 验证不同类型的工作项
    for (let i = 0; i < currentReport.value.workItems.length; i++) {
        const item = currentReport.value.workItems[i]

        // 公共验证
        if (!item.itemId) {
            ElMessage.warning(`请选择第${i + 1}个工作项的项目名称`)
            return false
        }

        if (!item.content) {
            ElMessage.warning(`请填写第${i + 1}个工作项的内容`)
            return false
        }

        // 按类型验证
        switch (item.workType) {
            case 1: // 别人安排的工作
                if (!item.assigner) {
                    ElMessage.warning(`请填写【别人安排的工作】工作项的安排人`)
                    return false
                }
                if (item.result !== 0 && parseFloat(item.timeSpent) <= 0) {
                    ElMessage.warning(`【别人安排的工作】工作项的耗时必须大于0`)
                    return false
                }
                if (item.result === undefined) {
                    ElMessage.warning(`请选择【别人安排的工作】工作项的结果`)
                    return false
                }
                break

            case 2: // 安排别人的工作
                if (!item.assigner) {
                    ElMessage.warning(`【安排别人的工作】的工作项被安排人不允许为空`)
                    return false
                }
                if (item.result === undefined) {
                    ElMessage.warning(`请选择【安排别人的工作】的工作项的结果`)
                    return false
                }
                break

            case 3: // 其他工作内容
                if (!item.assigner) {
                    ElMessage.warning(`请填写【其他工作内容】工作项的相关人员`)
                    return false
                }
                if (item.result !== 0 && parseFloat(item.timeSpent) <= 0) {
                    ElMessage.warning(`【其他工作内容】的工作项的耗时必须大于0`)
                    return false
                }
                if (item.result === undefined) {
                    ElMessage.warning(`请选择【其他工作内容】工作项的结果`)
                    return false
                }
                break

            case 4: // 市场部沟通
                if (!item.assigner) {
                    ElMessage.warning(`请填写【市场部沟通】工作项的市场人员`)
                    return false
                }
                if (item.result === undefined) {
                    ElMessage.warning(`请选择【市场部沟通】工作项的结果`)
                    return false
                }
                break

            case 5: // 标注内容
                if (!item.assigner) {
                    ElMessage.warning(`请填写【标注内容】工作项的甲方人员`)
                    return false
                }
                if (item.result === undefined) {
                    ElMessage.warning(`请选择【标注内容】工作项的结果`)
                    return false
                }
                break
        }
    }

    return true
}

// 获取项目名称
const getProjectName = (id: number) => {
    const project = filteredProjects.value.find(p => p.value === id);
    return project ? project.label : '未知项目';
};

// 获取结果文本
const getResultText = (result: number) => {
    switch (result) {
        case 0: return '未开始';
        case 1: return '未完成';
        case 2: return '完成';
        default: return '未知状态';
    }
};

const getResultTagClass = (result: number) => {
    if (result === 2) return 'tag-success'
    if (result === 1) return 'tag-warning'
    return 'tag-info'
}

const mapApiResultToInternal = (raw: any): 0 | 1 | 2 => {
    const val = Number(raw ?? 0);
    if (val === 0 || val === 1 || val === 2) return val as 0 | 1 | 2;
    return 0;
};

// 提交日报
const dailyType = ref(2);
const createDaily = async () => {
    try {
        // 检查日报日期是否早于当前时间前3天
        const reportDate = new Date(currentReport.value.dailyDate);
        const threeDaysAgo = new Date();
        threeDaysAgo.setDate(threeDaysAgo.getDate() - 3);
        threeDaysAgo.setHours(0, 0, 0, 0);

        if (reportDate < threeDaysAgo) {
            try {
                await ElMessageBox.confirm(
                    '日报超过3天,消耗一次补交次数,是否继续?',
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                );
            } catch {
                return false;
            }
        }

        const { data } = await CreateDaily({
            "dailyId": activeReportId.value,
            "dailyType": dailyType.value,
            "dailyDate": currentReport.value.dailyDate,
            "itemDailyList": currentReport.value.workItems
        });

        if (data.code == 200) {
            getDailyList();
            isEdite.value = true;
            activeTab.value = dailyType.value === 1 ? 2 : 1;
            ElMessage.success(data.msg);
            return true;
        } else {
            ElMessage.error(data.msg);
            return false;
        }
    } catch (error: any) {
        ElMessage.error('提交失败，请重试');
        return false;
    }
};

// 保存日报
const saveReport = async (submit: number) => {
    // 如果正在加载中，直接返回
    if (loading.value) return;

    loading.value = true; // 立即设置加载状态
    dailyType.value = submit; // 设置当前操作类型

    try {
        // 验证所有表单
        const isValid = await validateAllForms();
        if (!isValid) {
            loading.value = false;
            return;
        }

        // 获取格式化日期
        const reportDate = formatDate(currentReport.value.dailyDate);

        // 根据操作类型设置确认信息
        const action = submit === 1 ? '提交' : '保存草稿';
        const confirmMessage = `确定要${action} ${reportDate} 的日报吗？`;

        // 显示确认对话框
        await ElMessageBox.confirm(confirmMessage, `${action}确认`, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        isReturn.value = false;

        // 调用创建日报API
        const success = await createDaily();
        if (success) {
            // 清空表单引用数组
            otherForms.value = [];
            marketForms.value = [];
            annotationForms.value = [];
        }
    } catch (error: any) {
        // 用户点击取消时不执行任何操作
        console.log('用户取消操作');
    } finally {
        loading.value = false;
    }
};

// 查询日报记录
const getDailyList = async (loadMore = false) => {
    if (loadMore) {
        if (loadingMore.value || noMoreData.value) return
        loadingMore.value = true
        currentPage.value += 1
    } else {
        currentPage.value = 1
        noMoreData.value = false
    }

    try {
        const { data } = await GetDailyList({
            searchKeyword: searchKeyword.value || '',
            selectedDepartment: activeTab.value === 3 ? selectedDepartment.value : '',
            monthTime: selectedMonth.value || '',
            userName: activeTab.value === 3 ? selectedAuthor.value : '',
            dailyType: activeTab.value === 3 ? 3 : (activeTab.value === 1 ? 2 : 1),
            page: currentPage.value,
            pageSize: pageSize
        });

        if (data.code == 200) {
            if (loadMore) {
                // 追加数据
                reports.value = [...reports.value, ...(data.data || [])]
            } else {
                // 全新加载
                reports.value = data.data || []
            }

            // 检查是否还有更多数据
            noMoreData.value = (data.data || []).length < pageSize

            isViewMode.value = true
        } else {
            console.error('获取日报列表失败:', data.msg);
            ElMessage.error(data.msg || '获取日报列表失败')
            // 如果获取失败，至少显示空数组，避免undefined
            if (!loadMore) {
                reports.value = []
            }
        }
    } catch (error: any) {
        console.error('获取日报列表异常:', error);
        ElMessage.error('获取日报列表失败，请检查网络连接');
        // 如果获取失败，至少显示空数组，避免undefined
        if (!loadMore) {
            reports.value = []
        }
    } finally {
        loadingMore.value = false
    }
}

// 添加滚动加载方法
const handleScroll = () => {
    if (activeTab.value !== 3) return // 只在全部日报下启用懒加载

    const container = document.querySelector('.report-list-container')
    if (!container) return

    // 检查是否滚动到底部
    const { scrollTop, scrollHeight, clientHeight } = container
    if (scrollHeight - scrollTop <= clientHeight + 50 && !loadingMore.value && !noMoreData.value) {
        getDailyList(true)
    }
}

//获取可选未完成安排需求
const getMyDailyOneToMany = async () => {
    try {
        const { data } = await GetMyDailyOneToMany()
        if (data.code === 200) {
            // 获取当前已存在的工作项ID集合，使用 cardId + workType 组合作为唯一标识
            const existingItems = new Set<string>();
            if (currentReport.value.workItems) {
                currentReport.value.workItems.forEach(item => {
                    if (item.cardId) {
                        existingItems.add(`${item.cardId}_${item.workType}`);
                    }
                });
            }

            // 添加别人安排的工作（只添加未存在的）
            if (data.data.assignedTasks && data.data.assignedTasks.length > 0) {
                data.data.assignedTasks.forEach((task: any) => {
                    const uniqueId = `${task.cardId}_1`; // 1 表示别人安排的工作类型
                    if (!existingItems.has(uniqueId)) {
                        if (task.isTrue1 == 1) {
                            currentReport.value.workItems.push({
                                workType: 1,
                                itemId: task.projectId,
                                assigner: task.assigner,
                                content: `${task.title}\n${task.content}`,
                                timeSpent: String(task.timeSpent),
                                result: mapApiResultToInternal(task.isTrue1),
                                cardId: task.cardId
                            });
                        } else if (task.isTrue1 == 2) {
                            currentReport.value.workItems.push({
                                workType: 1,
                                itemId: task.projectId,
                                assigner: task.assigner,
                                content: `${task.title}\n${task.content}`,
                                timeSpent: task.timeSpent,
                                result: mapApiResultToInternal(task.isTrue1),
                                cardId: task.cardId
                            });
                        } else {
                            currentReport.value.workItems.push({
                                workType: 1,
                                itemId: task.projectId,
                                assigner: task.assigner,
                                content: `${task.title}\n${task.content}`,
                                timeSpent: task.timeSpent,
                                result: mapApiResultToInternal(task.isTrue1),
                                cardId: task.cardId
                            });
                        }

                        existingItems.add(uniqueId);
                    }
                });
            }

            // 添加安排别人的工作（只添加未存在的），按 isTrue2 作为默认结果
            if (data.data.assigningTasks && data.data.assigningTasks.length > 0) {
                data.data.assigningTasks.forEach((task: any) => {
                    const uniqueId = `${task.cardId}_2`; // 2 表示安排别人的工作类型
                    if (!existingItems.has(uniqueId)) {
                        if (task.isTrue2 == 1) {
                            currentReport.value.workItems.push({
                                workType: 2,
                                itemId: task.projectId,
                                assigner: task.assigner,
                                content: `${task.title}\n${task.content}`,
                                timeSpent: task.timeSpent,
                                result: mapApiResultToInternal(task.isTrue2),
                                assignerResult: mapApiResultToInternal(task.isTrue1),
                                cardId: task.cardId
                            });
                        } else if (task.isTrue2 == 2) {
                            currentReport.value.workItems.push({
                                workType: 2,
                                itemId: task.projectId,
                                assigner: task.assigner,
                                content: `${task.title}\n${task.content}`,
                                timeSpent: task.timeSpent,
                                result: mapApiResultToInternal(task.isTrue2),
                                assignerResult: mapApiResultToInternal(task.isTrue1),
                                cardId: task.cardId
                            });
                        } else {
                            currentReport.value.workItems.push({
                                workType: 2,
                                itemId: task.projectId,
                                assigner: task.assigner,
                                content: `${task.title}\n${task.content}`,
                                timeSpent: task.timeSpent,
                                result: mapApiResultToInternal(task.isTrue2),
                                assignerResult: mapApiResultToInternal(task.isTrue1),
                                cardId: task.cardId
                            });
                        }
                        existingItems.add(uniqueId);
                    }
                });
            }
        } else {
            ElMessage.error(data.msg)
        }
    } catch (error: any) {
        ElMessage.error('获取可选未完成安排需求失败')
        console.error(error)
    }
}

// 滚动查看日报
const isLoadingReport = ref(false);
const scrollLock = ref(false); // 防止快速滚动时多次触发
// 新建日报初始化 loading
const isInitializing = ref(false);

// 添加滚轮事件监听
const setupWheelListener = () => {
    const mainContent = document.querySelector('.main-content');
    if (mainContent) {
        mainContent.addEventListener('wheel', handleWheelScroll as EventListener, { passive: false });
    }
};

// 移除滚轮事件监听
const removeWheelListener = () => {
    const mainContent = document.querySelector('.main-content');
    if (mainContent) {
        mainContent.removeEventListener('wheel', handleWheelScroll as EventListener);
    }
};

// 处理滚轮滚动
const handleWheelScroll = (e: WheelEvent) => {
    if (isLoadingReport.value || !isViewMode.value || !isEdite.value) {
        return;
    }

    // 如果鼠标当前位于评论列表等可独立滚动区域，放行滚动事件
    const isInCommentScrollable = (() => {
        let node = e.target as HTMLElement | null
        while (node) {
            if (node.classList && (node.classList.contains('comment-list') || node.classList.contains('mention-list'))) {
                return true
            }
            node = node.parentElement as HTMLElement | null
        }
        return false
    })()
    if (isInCommentScrollable) return

    const workItemsContainer = document.querySelector('.work-items-container') as HTMLElement;
    if (!workItemsContainer) return;

    // 检查是否已经滚动到顶部或底部
    const isAtTop = workItemsContainer.scrollTop === 0;
    const isAtBottom = workItemsContainer.scrollHeight - workItemsContainer.scrollTop <= workItemsContainer.clientHeight + 1;

    // 只有在顶部或底部时才处理
    if ((e.deltaY > 0 && !isAtBottom) || (e.deltaY < 0 && !isAtTop)) {
        return; // 允许正常滚动
    }

    // 阻止默认行为只在需要切换日报时
    e.preventDefault();

    if (e.deltaY > 0 && isAtBottom) {
        // 向下滚动且已在底部 - 加载下一个日报
        loadNextReport();
    } else if (e.deltaY < 0 && isAtTop) {
        // 向上滚动且已在顶部 - 加载上一个日报
        loadPrevReport();
    }
};

// 加载下一个日报
const loadNextReport = async () => {
    if (scrollLock.value || filteredReports.value.length === 0) return;

    const currentIndex = filteredReports.value.findIndex(report => report.ID === activeReportId.value);
    if (currentIndex < filteredReports.value.length - 1) {
        scrollLock.value = true;
        isLoadingReport.value = true;

        try {
            await loadReport(filteredReports.value[currentIndex + 1].ID);

            // 滚动到顶部
            const workItemsContainer = document.querySelector('.work-items-container') as HTMLElement;
            if (workItemsContainer) {
                workItemsContainer.scrollTop = 0;
            }
        } finally {
            isLoadingReport.value = false;
            setTimeout(() => {
                scrollLock.value = false;
            }, 500); // 500ms内防止重复触发
        }
    }
};

// 加载上一个日报
const loadPrevReport = async () => {
    if (scrollLock.value || filteredReports.value.length === 0) return;

    const currentIndex = filteredReports.value.findIndex(report => report.ID === activeReportId.value);
    if (currentIndex > 0) {
        scrollLock.value = true;
        isLoadingReport.value = true;

        try {
            await loadReport(filteredReports.value[currentIndex - 1].ID);

            // 滚动到底部
            const workItemsContainer = document.querySelector('.work-items-container') as HTMLElement;
            if (workItemsContainer) {
                workItemsContainer.scrollTop = workItemsContainer.scrollHeight;
            }
        } finally {
            isLoadingReport.value = false;
            setTimeout(() => {
                scrollLock.value = false;
            }, 500); // 500ms内防止重复触发
        }
    }
};

// 筛选相关函数
const isFilterExpanded = ref(false)
const toggleFilter = () => {
    isFilterExpanded.value = !isFilterExpanded.value
}

const clearFilters = () => {
    selectedMonth.value = `${new Date().getFullYear()}-${(new Date().getMonth() + 1).toString().padStart(2, '0')}`;
    selectedDepartment.value = 'all';
    selectedAuthor.value = 'all';
    getDailyList();
}

// 日期格式化函数
const formatDailyDate = (dateString: string) => {
    if (!dateString) {
        return '';
    }

    try {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) {
            return '';
        }
        const result = `${date.getFullYear()}年${(date.getMonth() + 1).toString().padStart(2, '0')}月${date.getDate().toString().padStart(2, '0')}日`;
        return result;
    } catch (error) {
        console.error('formatDailyDate: 日期格式化错误:', error);
        return '';
    }
};

/* ---------------- 评论相关逻辑 ---------------- */
const comments = ref<Comment[]>([])
const newComment = ref('')
const replyingTo = ref<number>()
const replyingToAuthor = ref<string>('')
const commentsLoading = ref(false)
const isSubmittingComment = ref(false)
const showMentionList = ref(false)
const filteredMentionUsers = ref<Staff[]>([])
const mentionStartIndex = ref(-1)
const mentionSearchText = ref('')

// 将扁平列表构造成树形层级
const buildCommentTree = (items: any[]): Comment[] => {
    const nodeMap = new Map<number, Comment>()
    const roots: Comment[] = []

    // 先创建所有节点
    for (const it of items) {
        nodeMap.set(it.ID, {
            ID: it.ID,
            userName: it.userName,
            checkDailyComments: it.checkDailyComments,
            time: it.createAt, // 保持原始时间，在显示时转换
            replyTo: it.replyTo || undefined,
            replyToAuthor: it.replyToAuthor || undefined,
            replies: []
        })
    }

    // 关联父子关系
    for (const it of items) {
        const node = nodeMap.get(it.ID)!
        if (it.replyTo && nodeMap.has(it.replyTo)) {
            const parent = nodeMap.get(it.replyTo)!
            parent.replies = parent.replies || []
            parent.replies.push(node)
        } else {
            roots.push(node)
        }
    }

    // 按时间排序（根与每层）
    const sortByTime = (arr: Comment[]) => {
        arr.sort((a, b) => new Date(a.time || '').getTime() - new Date(b.time || '').getTime())
        arr.forEach(c => c.replies && sortByTime(c.replies))
    }
    sortByTime(roots)
    return roots
}

const mapCommentsRecursive = (items: any[]): Comment[] => {
    return (items || []).map((it: any) => ({
        ID: it.ID,
        userName: it.userName,
        checkDailyComments: it.checkDailyComments,
        time: it.createAt, // 保持原始时间，在显示时转换
        replyTo: it.replyTo || undefined,
        replyToAuthor: it.replyToAuthor || undefined,
        replies: mapCommentsRecursive(it.replies || [])
    }))
}

const getComments = async () => {
    const id = activeReportId.value || currentReport.value.ID
    if (!id) return
    commentsLoading.value = true
    try {
        const { data } = await GetToComments(id)
        if (data.code == 200) {
            const list = data.data || []
            // 若接口已提供嵌套的 replies，直接递归映射；否则从扁平构建树
            const hasNested = Array.isArray(list) && list.some((i: any) => Array.isArray(i.replies) && i.replies.length > 0)
            comments.value = hasNested ? mapCommentsRecursive(list) : buildCommentTree(list)
            // 统计总条数（含子回复）
            totalCommentCount.value = countComments(comments.value)
        } else {
            ElMessage.error(data.msg)
        }
    } catch (error) {
        ElMessage.error('获取评论失败')
        console.error(error)
    } finally {
        commentsLoading.value = false
    }
}

const extractMentionedUsers = (text: string) => {
    const mentions = text.match(/@([^\s]+)/g) || []
    return mentions.map(m => m.substring(1))
}

const submitComment = async () => {
    const id = activeReportId.value || currentReport.value.ID
    if (!newComment.value.trim() || !id || isSubmittingComment.value) return
    
    isSubmittingComment.value = true
    try {
        const mentionedUsers = extractMentionedUsers(newComment.value)
        const { data } = await ToComments({
            dailyId: id,
            newComment: newComment.value,
            mentionedUsers,
            replyTo: replyingTo.value || undefined,
            replyToAuthor: replyingTo.value ? replyingToAuthor.value : undefined
        })
        if (data.code == 200) {
            newComment.value = ''
            cancelReply()
            getComments()
            ElMessage.success('评论提交成功')
        } else {
            ElMessage.error(data.msg)
        }
    } catch (error) {
        ElMessage.error('评论提交失败')
        console.error(error)
    } finally {
        isSubmittingComment.value = false
    }
}

const handleReplyClick = (comment: Comment) => {
    replyingTo.value = comment.ID
    replyingToAuthor.value = comment.userName || ''
    newComment.value = `@${replyingToAuthor.value} `
    
    // 确保评论区域展开
    if (!showCommentSection.value) {
        showCommentSection.value = true
    }
    
    // 移动端自动滚动到输入框
    nextTick(() => {
        scrollToCommentInput()
    })
}

// 检测是否为移动端设备
const isMobile = () => {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || 
           window.innerWidth <= 768
}

// 滚动到评论输入框
const scrollToCommentInput = () => {
    if (!isMobile()) return
    
    const commentInput = document.querySelector('.comment-input textarea') as HTMLElement
    const commentActions = document.querySelector('.comment-actions') as HTMLElement
    
    if (commentInput && commentActions) {
        // 延迟执行，确保DOM更新完成
        setTimeout(() => {
            // 获取按钮的位置
            const actionsRect = commentActions.getBoundingClientRect()
            const viewportHeight = window.innerHeight
            const keyboardHeight = viewportHeight * 0.4 // 估算键盘高度
            
            // 计算按钮底部位置
            const buttonBottom = window.pageYOffset + actionsRect.bottom
            const availableHeight = viewportHeight - keyboardHeight
            
            // 确保按钮在可见区域内，留出更多边距
            const scrollTop = buttonBottom - availableHeight + 50 // 增加边距到50px
            
            // 平滑滚动到合适位置
            window.scrollTo({
                top: Math.max(0, scrollTop),
                behavior: 'smooth'
            })
            
            // 聚焦到输入框
            setTimeout(() => {
                commentInput.focus()
                // 将光标移动到文本末尾
                const textarea = commentInput as HTMLTextAreaElement
                const textLength = textarea.value.length
                textarea.setSelectionRange(textLength, textLength)
            }, 100)
        }, 200) // 增加延迟，确保DOM完全更新
    }
}

// 滚动到评论区域（用于展开时）
const scrollToCommentSection = () => {
    if (!isMobile()) return
    
    const commentSection = document.querySelector('.comment-section') as HTMLElement
    if (commentSection) {
        // 延迟执行，确保DOM更新完成
        setTimeout(() => {
            commentSection.scrollIntoView({ 
                behavior: 'smooth', 
                block: 'start',
                inline: 'nearest'
            })
        }, 100)
    }
}

// 处理输入框焦点事件
const handleInputFocus = () => {
    if (isMobile()) {
        // 移动端输入框获得焦点时，延迟滚动以确保键盘弹出后位置正确
        setTimeout(() => {
            const commentInput = document.querySelector('.comment-input textarea') as HTMLElement
            const commentActions = document.querySelector('.comment-actions') as HTMLElement
            
            if (commentInput && commentActions) {
                // 获取按钮的位置
                const actionsRect = commentActions.getBoundingClientRect()
                const viewportHeight = window.innerHeight
                const keyboardHeight = viewportHeight * 0.4 // 估算键盘高度
                
                // 计算按钮底部位置
                const buttonBottom = window.pageYOffset + actionsRect.bottom
                const availableHeight = viewportHeight - keyboardHeight
                
                // 确保按钮在可见区域内，增加边距
                const scrollTop = buttonBottom - availableHeight + 60 // 增加边距到60px
                
                // 平滑滚动到合适位置
                window.scrollTo({
                    top: Math.max(0, scrollTop),
                    behavior: 'smooth'
                })
                
                // 确保光标在正确位置
                setTimeout(() => {
                    const textarea = commentInput as HTMLTextAreaElement
                    textarea.focus()
                    // 将光标移动到文本末尾
                    const textLength = textarea.value.length
                    textarea.setSelectionRange(textLength, textLength)
                }, 100)
            }
        }, 400) // 增加延迟，确保键盘完全弹出
    }
}

const cancelReply = () => {
    clearReplyState()
    
    // 移动端取消回复后恢复滚动
    if (isMobile()) {
        restoreScrollAfterCancel()
    }
}

// 移动端取消回复后恢复滚动
const restoreScrollAfterCancel = () => {
    if (!isMobile()) return
    
    // 延迟执行，确保DOM更新完成
    setTimeout(() => {
        // 保存当前滚动位置
        const currentScrollTop = window.pageYOffset
        
        // 强制重新计算页面高度和滚动
        const body = document.body
        const html = document.documentElement
        
        // 临时移除可能影响滚动的样式
        const originalOverflow = body.style.overflow
        const originalHeight = body.style.height
        
        // 重置页面高度计算
        body.style.overflow = 'auto'
        body.style.height = 'auto'
        
        // 强制重新计算
        const scrollHeight = Math.max(
            body.scrollHeight,
            body.offsetHeight,
            html.clientHeight,
            html.scrollHeight,
            html.offsetHeight
        )
        
        // 恢复原始样式
        body.style.overflow = originalOverflow
        body.style.height = originalHeight
        
        // 如果当前滚动位置为0，尝试滚动到合理位置
        if (currentScrollTop === 0 && scrollHeight > window.innerHeight) {
            // 尝试滚动到评论区域
            const commentSection = document.querySelector('.comment-section') as HTMLElement
            if (commentSection) {
                const rect = commentSection.getBoundingClientRect()
                const targetScrollTop = window.pageYOffset + rect.top - 100 // 留出一些边距
                
                window.scrollTo({
                    top: Math.max(0, targetScrollTop),
                    behavior: 'smooth'
                })
            }
        } else if (currentScrollTop > 0) {
            // 保持当前滚动位置，但确保页面可以正常滚动
            window.scrollTo({
                top: currentScrollTop,
                behavior: 'auto'
            })
        }
        
        // 触发resize事件，让浏览器重新计算视口
        setTimeout(() => {
            window.dispatchEvent(new Event('resize'))
        }, 100)
    }, 300) // 增加延迟，确保键盘完全收起
}

const handleCommentInput = (e: Event) => {
    console.log('handleCommentInput triggered!')
    const target = e.target as HTMLTextAreaElement | null
    if (!target) {
        console.log('No target element')
        return
    }
    const text = target.value
    const cursorPos = target.selectionStart || 0
    const lastAtPos = text.lastIndexOf('@', cursorPos - 1)

    // 如果当前处于提及模式，但触发该模式的原始 @ 已被删除或改变，则立即关闭
    if (showMentionList.value && mentionStartIndex.value >= 0) {
        const stillHasOriginAt = text.length > mentionStartIndex.value && text.charAt(mentionStartIndex.value) === '@'
        if (!stillHasOriginAt) {
            console.log('Origin @ removed -> close mention list')
            showMentionList.value = false
            mentionStartIndex.value = -1
            mentionSearchText.value = ''
            filteredMentionUsers.value = []
            return
        }
    }
    
    // 检查@符号是否被删除或光标位置是否有效
    const rawSearch = text.substring(lastAtPos + 1, cursorPos)
    const searchText = rawSearch.trim()
    console.log('Input check:', { text, cursorPos, lastAtPos, searchText, showMentionList: showMentionList.value })
    
    if (lastAtPos < 0 || cursorPos <= lastAtPos || searchText === '') {
        // 如果没有@符号、光标不在@符号之后、或者搜索文本为空，隐藏列表
        console.log('Closing mention list - no valid @ symbol or empty search')
        showMentionList.value = false
        mentionStartIndex.value = -1
        mentionSearchText.value = ''
        filteredMentionUsers.value = []
        return
    }
    
    // 更新搜索文本
    mentionSearchText.value = rawSearch

    // 如果检索词包含空格，认为结束@，立即关闭列表
    if (mentionSearchText.value.includes(' ')) {
        showMentionList.value = false
        mentionStartIndex.value = -1
        mentionSearchText.value = ''
        filteredMentionUsers.value = []
        return
    }
    
    // 如果当前没有显示@提及列表，但输入了@符号，则显示
    if (lastAtPos >= 0 && !showMentionList.value) {
        mentionStartIndex.value = lastAtPos
        showMentionList.value = true
    }
    
    // 如果已经显示列表，更新过滤结果
    if (showMentionList.value) {
        console.log('Updating mention filter:', { searchText: mentionSearchText.value, staffListLength: staffList.value.length })
        
        // 使用更智能的搜索算法
        filteredMentionUsers.value = staffList.value.filter(user => {
            const searchText = mentionSearchText.value.toLowerCase()
            const userName = user.name.toLowerCase()
            const userDept = (user.department || '').toLowerCase()
            
            // 支持姓名和部门的模糊搜索
            return userName.includes(searchText) || userDept.includes(searchText)
        }) as unknown as Staff[]
        
        console.log('Filtered results:', filteredMentionUsers.value.length)
        
        // 按匹配度排序：完全匹配 > 开头匹配 > 包含匹配
        filteredMentionUsers.value.sort((a, b) => {
            const searchText = mentionSearchText.value.toLowerCase()
            const aName = a.name.toLowerCase()
            const bName = b.name.toLowerCase()
            
            // 完全匹配优先级最高
            if (aName === searchText && bName !== searchText) return -1
            if (bName === searchText && aName !== searchText) return 1
            
            // 开头匹配优先级次之
            const aStartsWith = aName.startsWith(searchText)
            const bStartsWith = bName.startsWith(searchText)
            if (aStartsWith && !bStartsWith) return -1
            if (bStartsWith && !aStartsWith) return 1
            
            // 按姓名长度排序，短的名字优先
            return aName.length - bName.length
        })
    }
}

const selectMentionUser = (user: any) => {
    if (mentionStartIndex.value >= 0 && user) {
        const textBefore = newComment.value.substring(0, mentionStartIndex.value)
        const textAfter = newComment.value.substring(mentionStartIndex.value + mentionSearchText.value.length + 1)
        newComment.value = `${textBefore}@${user.name} ${textAfter}`
        showMentionList.value = false
        nextTick(() => {
            const input = document.querySelector('.comment-input textarea') as HTMLTextAreaElement | null
            if (input) {
                input.focus()
                const cursor = mentionStartIndex.value + user.name.length + 2
                input.setSelectionRange(cursor, cursor)
            }
        })
    }
}

// 搜索文本高亮函数
const highlightSearchText = (text: string, searchText: string) => {
    if (!searchText) return text
    const regex = new RegExp(`(${searchText})`, 'gi')
    return text.replace(regex, '<mark class="search-highlight">$1</mark>')
}

// 统计评论总数（含子级）
const totalCommentCount = ref(0)
const countComments = (nodes: Comment[]): number => {
    let sum = 0
    for (const n of nodes) {
        sum += 1
        if (n.replies && n.replies.length) sum += countComments(n.replies)
    }
    return sum
}

// 整个评论区域展开/收起
const showCommentSection = ref(false)

// 移动端评论模态框
const showMobileCommentModal = ref(false)


// 处理移动端评论提交成功
const handleMobileCommentSubmitted = () => {
    // 刷新评论数据
    getComments()
}
const toggleCommentSection = () => {
    // 移动端使用模态框显示评论
    if (isMobile()) {
        showMobileCommentModal.value = true
        return
    }
    
    // 桌面端使用原有的展开/收起逻辑
    showCommentSection.value = !showCommentSection.value
    
    // 桌面端展开评论时自动滚动到评论区域并聚焦输入框
    if (showCommentSection.value) {
        nextTick(() => {
            scrollToCommentSection()
            // 自动聚焦到评论输入框
            const commentInput = document.querySelector('.comment-input textarea') as HTMLTextAreaElement | null
            if (commentInput) {
                commentInput.focus()
            }
        })
    }
}

// 移动端键盘收起事件处理
const handleMobileKeyboardHide = () => {
    if (!isMobile()) return
    
    // 延迟执行，确保键盘完全收起
    setTimeout(() => {
        // 检查页面是否可以正常滚动
        const body = document.body
        const html = document.documentElement
        const scrollHeight = Math.max(
            body.scrollHeight,
            body.offsetHeight,
            html.clientHeight,
            html.scrollHeight,
            html.offsetHeight
        )
        
        // 如果页面高度大于视口高度但无法滚动，尝试修复
        if (scrollHeight > window.innerHeight && window.pageYOffset === 0) {
            // 强制重新计算页面高度
            body.style.height = 'auto'
            body.style.overflow = 'auto'
            
            // 触发resize事件
            window.dispatchEvent(new Event('resize'))
        }
    }, 500)
}

// 初始化
onMounted(() => {
    document.addEventListener('keydown', handleKeyDown)
    document.addEventListener('click', handleClickOutside)
    
    // 移动端添加键盘收起事件监听
    if (isMobile()) {
        // 监听视口高度变化（键盘收起时视口高度会增加）
        let lastViewportHeight = window.innerHeight
        const handleResize = () => {
            const currentHeight = window.innerHeight
            if (currentHeight > lastViewportHeight) {
                // 视口高度增加，可能是键盘收起了
                handleMobileKeyboardHide()
            }
            lastViewportHeight = currentHeight
        }
        
        window.addEventListener('resize', handleResize)
        
        // 在组件卸载时移除监听器
        onUnmounted(() => {
            window.removeEventListener('resize', handleResize)
        })
    }
    
    activeReportId.value = 0;
    setupWheelListener();

    // 确保用户信息已获取
    if (!userStore.userInfo.nickName) {
        userStore.getUseInfo().then(() => {
            initializeData();
        }).catch(error => {
            console.error('获取用户信息失败:', error);
            // 即使获取用户信息失败，也尝试初始化数据
            initializeData();
        });
    } else {
        initializeData();
    }
})

// 数据初始化函数
const initializeData = async () => {
    try {
        // 并行获取数据
        await Promise.all([
            getItemList(),
            getDailyList()
        ]);

        // 初始化时获取所有部门的用户
        await getAllUsers('all');

        // 添加滚动监听
        const container = document.querySelector('.report-list-container')
        if (container) {
            container.addEventListener('scroll', handleScroll)
        }

    } catch (error) {
        console.error('数据初始化失败:', error);
        ElMessage.error('数据初始化失败，请刷新页面重试');
    }
}

// 清理回复状态的函数
const clearReplyState = () => {
    replyingTo.value = undefined
    replyingToAuthor.value = ''
    newComment.value = ''
    showMentionList.value = false
    filteredMentionUsers.value = []
    mentionStartIndex.value = -1
    mentionSearchText.value = ''
}

// 点击外部区域关闭@提及列表
const handleClickOutside = (e: Event) => {
    const target = e.target as HTMLElement
    const mentionContainer = document.querySelector('.mention-list-container')
    const commentInput = document.querySelector('.comment-input')
    
    if (mentionContainer && !mentionContainer.contains(target) && 
        commentInput && !commentInput.contains(target)) {
        showMentionList.value = false
    }
}

// 监听标签页切换，清理回复状态
watch(activeTab, () => {
    clearReplyState()
})

// 监听活跃报告ID变化，清理回复状态
watch(activeReportId, () => {
    clearReplyState()
})

// 路由离开前清理回复状态
onBeforeRouteLeave(() => {
    clearReplyState()
})

// 在组件卸载时移除监听
onUnmounted(() => {
    document.removeEventListener('keydown', handleKeyDown)
    document.removeEventListener('click', handleClickOutside)
    removeWheelListener();
    // 移除滚动监听
    const container = document.querySelector('.report-list-container')
    if (container) {
        container.removeEventListener('scroll', handleScroll)
    }
    // 清理回复状态
    clearReplyState()
});


</script>

<style scoped>
/* 整体布局样式 */
.daily-report-system {
    height: calc(100vh - 90px);
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    /* 整体不要截断，交给子容器控制滚动 */
    overflow: hidden;
    display: flex;
}

.sidebar {
    width: 300px;
    background-color: white;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
    height: 100%;
    overflow: hidden;
    border-radius: 8px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
}

.main-content {
    position: relative;
    flex: 1;
    padding-left: 15px;
    height: 100%;
    /* 允许内部滚动 */
    overflow: hidden;
}

.tab-container {
    background-color: white;
    width: 100%;
    /* 让上方区域按内容高度自适应，避免占满导致列表区无空间 */
    height: auto;
    overflow: visible;
    display: flex;
    flex-direction: column;
    flex: 0 0 auto;
}

.tabs {
    padding: 0 16px;
    flex-shrink: 0;
}

.filter-container {
    /* 避免高度收缩导致下方列表区域不可见 */
    flex-shrink: 0;
    overflow: visible;
}

.report-list-container {
    width: 100%;
    /* 确保列表区域可以分配剩余空间滚动显示 */
    flex: 1 1 auto;
    overflow-y: auto;
    padding: 0 10px;
    min-height: 0;
}

.new-report-btn-container {
    padding: 12px;
    position: sticky;
    top: 0;
    z-index: 5;
    background: #ffffff;
    border-bottom: 1px solid #f0f2f5;
  margin-bottom: 5px;
}

.new-report-btn {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    border-radius: 12px;
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    color: #fff;
    font-weight: 700;
    letter-spacing: 0.5px;
    box-shadow: 0 6px 16px rgba(59, 130, 246, 0.25);
    transition: transform 0.12s ease, box-shadow 0.12s ease, filter 0.12s ease;
}

.new-report-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 10px 22px rgba(29, 78, 216, 0.28);
    filter: brightness(1.03);
}

.new-report-btn:active {
    transform: translateY(0);
    box-shadow: 0 6px 16px rgba(29, 78, 216, 0.22);
    filter: brightness(0.98);
}

.report-item {
    background: #ffffff;
    border: 1px solid #e4e7ed;
    border-radius: 10px;
    padding: 5px;
    margin-bottom: 10px;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    overflow: hidden;
}

.report-item:hover {
    transform: translateY(-1px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
    border-color: #409eff;
  border-left: 3px solid #409eff!important;
}

.report-item.active-report {
    border-color: #409eff;
    background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
    box-shadow: 0 3px 15px rgba(64, 158, 255, 0.12);
  border-left: 3px solid #409eff!important;
}

.report-item.draft-report {
    border-left: 3px solid #909399;
}

.report-item.submitted-report {
    border-left: 3px solid #67c23a;
}

.report-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 10px;
}

.report-left-section {
    display: flex;
    flex-direction: column;
    gap: 4px;
    flex: 1;
}

.report-right-section {
    display: flex;
    justify-content: flex-end;
    align-items: flex-start;
}

.report-date-section {
    display: flex;
    flex-direction: column;
    gap: 3px;
}

.report-date {
    font-size: 12px;
    font-weight: 500;
    color: #909399;
    line-height: 1.3;
}

.report-author-section {
    display: flex;
    align-items: center;
    gap: 6px;
}

.author-avatar {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    font-weight: 600;
    font-size: 11px;
}

.report-author {
    font-size: 13px;
    color: #303133;
    font-weight: 600;
}

.report-status-section {
    display: flex;
    justify-content: flex-end;
}

.status-icon {
    margin-right: 3px;
    font-size: 10px;
}

.report-preview {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 5px;
    border-top: 1px solid #f0f0f0;
}

.work-items-count,
.readers-count {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 10px;
    color: #909399;
    padding: 3px 6px;
    background: #f8f9fa;
    border-radius: 6px;
    transition: all 0.2s ease;
}

.work-items-count,
.readers-count span{
  font-size: 12px;
}

.work-items-count:hover,
.readers-count:hover {
    background: #e9ecef;
    color: #606266;
}

.count-icon {
    font-size: 14px;
    color: #409eff;
}

/* 已读未读标签样式升级 */
.read-tag {
    background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
    color: white;
    border: none;
    font-weight: 500;
    padding: 3px 8px;
    border-radius: 12px;
    box-shadow: 0 1px 4px rgba(103, 194, 58, 0.2);
    font-size: 10px;
}

.unread-tag {
    background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
    color: white;
    border: none;
    font-weight: 500;
    padding: 3px 8px;
    border-radius: 12px;
    box-shadow: 0 1px 4px rgba(245, 108, 108, 0.2);
    font-size: 10px;
}

.read-tag:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 6px rgba(103, 194, 58, 0.3);
}

.unread-tag:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 6px rgba(245, 108, 108, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
    /* 移动端整体布局优化 */
    .daily-report-system {
        height: 100vh;
        flex-direction: column;
    }
    
    .sidebar {
        width: 100%;
        height: auto;
        max-height: 40vh;
        overflow-y: auto;
        border-radius: 0;
        box-shadow: none;
        border-bottom: 1px solid #e2e8f0;
    }
    
    .content-area {
        flex: 1;
        height: calc(100vh - 40vh);
        min-height: 60vh;
    }
    
    .filter-container {
        padding: 12px 16px;
        margin: 12px 0;
    }

    .filter-header {
        flex-direction: column;
        gap: 12px;
        align-items: stretch;
    }

    .filter-title-section {
        justify-content: center;
    }

    .filter-content {
        padding: 16px 0;
    }

    .filter-item {
        gap: 6px;
        margin-bottom: 16px;
    }

    .filter-label {
        font-size: 13px;
    }

    .filter-actions {
        flex-direction: column;
        gap: 8px;
    }

    .clear-btn {
        width: 100%;
        justify-content: center;
    }

    .report-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }

    .report-preview {
        flex-direction: column;
        align-items: flex-start;
        gap: 6px;
    }
}

/* 日报详情页面样式升级 */
.report-card {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    padding: 15px;
    background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid #e2e8f0;
}

.detail-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 2px solid #f1f5f9;
}

.report-title {
    font-size: 28px;
    font-weight: 700;
    color: #1e293b;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 12px;
}

.view-mode-title {
    color: #475569;
}

.readers-tag {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    color: white;
    border: none;
    font-weight: 600;
    padding: 8px 16px;
    border-radius: 20px;
    box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.2s ease;
}

.readers-tag:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
}

.header-right {
    display: flex;
    align-items: center;
    gap: 16px;
}

.search-input {
    width: 300px;
}

.search-input :deep(.el-input__wrapper) {
    border-radius: 12px;
    border: 1px solid #d1d5db;
    transition: all 0.2s ease;
}

.search-input :deep(.el-input__wrapper:hover) {
    border-color: #3b82f6;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.search-input :deep(.el-input__wrapper.is-focus) {
    border-color: #3b82f6;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}

.action-buttons {
    display: flex;
    gap: 12px;
}

.action-btn {
    border-radius: 10px;
    font-weight: 600;
    padding: 10px 20px;
    transition: all 0.2s ease;
    border: none;
}

.action-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 结果下拉的颜色边框状态 */
.result-select.tag-success :deep(.el-input__wrapper) {
    border-color: #67c23a;
}
.result-select.tag-warning :deep(.el-input__wrapper) {
    border-color: #e6a23c;
}
.result-select.tag-info :deep(.el-input__wrapper) {
    border-color: #909399;
}

/* 选中后输入框中的文字与背景也同步上色 */
.result-select.tag-success :deep(.el-input__inner) {
    color: #529b2e;
    font-weight: 600;
}
.result-select.tag-warning :deep(.el-input__inner) {
    color: #b88230;
    font-weight: 600;
}
.result-select.tag-info :deep(.el-input__inner) {
    color: #606266;
    font-weight: 600;
}

.result-select.tag-success :deep(.el-input__wrapper) {
    background-color: rgba(103, 194, 58, 0.06);
}
.result-select.tag-warning :deep(.el-input__wrapper) {
    background-color: rgba(230, 162, 60, 0.06);
}
.result-select.tag-info :deep(.el-input__wrapper) {
    background-color: rgba(144, 147, 153, 0.06);
}

/* 隐藏原始选中的文本，只保留前缀 tag 展示，避免重复 */
.result-select :deep(.el-select__selected-item) {
    display: none;
}

/* 让输入框根据前缀内容自适应宽度 */
.result-select :deep(.el-input) {
    width: auto;
}
.result-select :deep(.el-input__wrapper) {
    padding-right: 8px;
    padding-left: 8px;
}
.result-select :deep(.el-input__prefix) {
    padding-right: 4px;
}

.btn-icon {
    margin-right: 6px;
}

/* 工作内容区域样式升级 */
.report-meta-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 16px 20px;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border-radius: 12px;
    border: 1px solid #e2e8f0;
}

.meta-text {
    color: #475569;
    font-weight: 600;
    font-size: 16px;
}

.date-picker {
    width: 200px;
}

.date-picker :deep(.el-input__wrapper) {
    border-radius: 10px;
    border: 1px solid #d1d5db;
    transition: all 0.2s ease;
}

/* 标题行内联日期选择器样式 */
.inline-date-picker {
    margin-left: 12px;
}
.inline-date-picker :deep(.el-input__wrapper) {
    height: 32px;
    border-radius: 8px;
    border: 1px solid #d1d5db;
}
.inline-date-picker :deep(.el-input__inner) {
    font-size: 14px;
}

.date-picker :deep(.el-input__wrapper:hover) {
    border-color: #3b82f6;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.work-content-container {
    display: flex;
    flex-direction: column;
    height: calc(100% - 75px);
    overflow: hidden;
    background: #ffffff;
    border-radius: 12px;
    border: 1px solid #e2e8f0;
    padding: 15px;
}

/* 新增日报时，工作内容区域占满整个高度 */
.work-content-container.new-report-mode {
    height: calc(100% - 20px);
}

.work-content-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 2px solid #f1f5f9;
}

.work-content-header-left {
    display: flex;
    align-items: center;
}

.work-content-header-right {
    display: flex;
    align-items: center;
}

.mobile-comment-btn {
    border-radius: 6px;
    font-weight: 500;
    transition: all 0.2s ease;
    font-size: 12px;
    padding: 6px 12px;
    display: flex;
    align-items: center;
    gap: 4px;
}

.mobile-comment-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

.content-icon {
    color: #3b82f6;
    margin-right: 12px;
    font-size: 20px;
}

.content-title {
    font-size: 20px;
    font-weight: 700;
    margin: 0;
    color: #1e293b;
}

.work-items-container {
    flex: 1;
    overflow-y: auto;
    min-height: 0;
    padding-right: 12px;
    max-height: 58%;
}

.work-items-container.full-height {
    max-height: 100%;
}

/* 新增日报时，工作内容区域占满更多空间 */
.new-report-mode .work-items-container {
    max-height: 85%;
}

.work-items-container::-webkit-scrollbar {
    width: 6px;
}

.work-items-container::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 3px;
}

.work-items-container::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 3px;
}

.work-items-container::-webkit-scrollbar-thumb:hover {
    background: #94a3b8;
}

/* 工作项部分样式升级 */
.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 5px 0 5px 0;
    padding: 12px 16px;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border-radius: 10px;
    border: 1px solid #e2e8f0;
}

.section-title {
    font-size: 16px;
    font-weight: 600;
    margin: 0;
    color: #374151;
    display: flex;
    align-items: center;
    gap: 8px;
}

.add-btn {
    margin-left: 12px;
    display: flex;
    align-items: center;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.2s ease;
}

.add-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.work-item {
    margin-bottom: 0;
    padding: 14px 14px 0 14px;
    border-radius: 12px;
    background: #ffffff;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
    border: 1px solid #e5e7eb;
    transition: all 0.2s ease;
    position: relative;
}
.work-item::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 3px;
    background: #3b82f6;
}
.plain-text-item{
  margin-bottom: 10px;
}
/* 工作项网格容器 */
.work-item-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
    grid-gap: 12px;
}

.work-item:hover {
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
    transform: translateY(-1px);
}

.work-item:nth-child(odd)::before {
    background: #10b981;
}

.work-item:nth-child(even)::before {
    background: #f59e0b;
}

.work-item:nth-child(3n)::before {
    background: #8b5cf6;
}

/* 评论区域 */
.comment-section { 
    margin-top: 16px;
    border-top: 2px solid #f1f5f9;
    padding-top: 16px;
    background: linear-gradient(135deg, #fafbfc 0%, #ffffff 100%);
    border-radius: 12px;
    padding: 16px;
}
.comment-header { 
    display: flex; 
    align-items: center; 
    justify-content: space-between;
    margin-bottom: 8px;
    padding: 8px 0;
}

.comment-header-left {
    display: flex;
    align-items: center;
    gap: 8px;
}

.comment-header-right {
    display: flex;
    align-items: center;
    gap: 8px;
}

.comment-count-tag { 
    margin: 0;
}

.readers-count-tag {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
    border: none;
    font-weight: 500;
    font-size: 12px;
}

.comment-toggle-btn {
    border-radius: 6px;
    font-weight: 500;
    transition: all 0.2s ease;
}

.comment-toggle-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

.comment-count-badge {
    margin-left: 6px;
    background: rgba(255, 255, 255, 0.2);
    color: white;
    border: 1px solid rgba(255, 255, 255, 0.3);
    font-weight: 600;
    font-size: 11px;
    min-width: 18px;
    height: 18px;
    line-height: 16px;
    padding: 0 4px;
    border-radius: 9px;
}
.comment-list { 
    max-height: 400px; 
    overflow-y: auto; 
    margin-top: 12px; 
    padding-right: 12px;
    overscroll-behavior: contain;
    background: #ffffff;
    border-radius: 8px;
    padding: 8px 8px 8px 8px;
    box-shadow: inset 0 2px 4px rgba(0,0,0,0.06);
    /* 确保滚动条可见 */
    scrollbar-width: thin;
    scrollbar-color: #cbd5e1 #f1f5f9;
}

/* 自定义滚动条样式 */
.comment-list::-webkit-scrollbar {
    width: 6px;
}

.comment-list::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 3px;
}

.comment-list::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 3px;
}

.comment-list::-webkit-scrollbar-thumb:hover {
    background: #94a3b8;
}
.comment-input { margin-top: 6px; }
.comment-actions { 
    margin-top: 8px; 
    text-align: right; 
}

.comment-actions .el-button {
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.comment-actions .el-button:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.comment-actions .el-button.is-loading {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    border-color: #3b82f6;
    color: white;
}
.reply-info { margin-bottom: 6px; color: #606266; background: #f5f7fa; padding: 6px 8px; border-radius: 8px; border: 1px dashed #e5e7eb; }

/* @提及人员列表样式 */
.mention-list-container { 
    position: relative; 
    margin-bottom: 20px;
}

.mention-list { 
    position: absolute; 
    left: 0; 
    right: 0; 
    bottom: 100%; 
    margin-bottom: 55px;
    background: #fff; 
    border: 1px solid #e5e7eb; 
    border-radius: 12px; 
    z-index: 1000; 
    max-height: 160px; 
    overflow: hidden;
    box-shadow: 0 12px 32px rgba(0,0,0,0.12), 0 2px 8px rgba(0,0,0,0.08);
    backdrop-filter: blur(8px);
    animation: mentionSlideUp 0.2s ease-out;
}

@keyframes mentionSlideUp {
    from {
        opacity: 0;
        transform: translateY(8px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.mention-header {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border-bottom: 1px solid #e2e8f0;
    border-radius: 12px 12px 0 0;
}

.mention-icon {
    color: #3b82f6;
    margin-right: 8px;
    font-size: 16px;
}

.mention-title {
    font-weight: 600;
    color: #1e293b;
    font-size: 14px;
    flex: 1;
}

.mention-count {
    background: #3b82f6;
    color: white;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
}

.mention-items {
    max-height: 100px;
    overflow-y: auto;
    padding: 4px 0;
}

.mention-item { 
    display: flex;
    align-items: center;
    padding: 8px 12px; 
    cursor: pointer; 
    transition: all 0.2s ease;
    border-bottom: 1px solid #f1f5f9;
    position: relative;
}

.mention-item:last-child {
    border-bottom: none;
}

.mention-item:hover { 
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    transform: translateX(2px);
}

.mention-item:active {
    transform: translateX(0);
    background: #e2e8f0;
}

.mention-avatar {
    margin-right: 12px;
    flex-shrink: 0;
}

.user-avatar {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    color: white;
    font-weight: 600;
    font-size: 14px;
}

.mention-info {
    flex: 1;
    min-width: 0;
}

.mention-name {
    font-weight: 500;
    color: #1e293b;
    font-size: 14px;
    margin-bottom: 2px;
    line-height: 1.4;
}

.mention-department {
    display: flex;
    align-items: center;
    color: #64748b;
    font-size: 12px;
    gap: 4px;
}

.dept-icon {
    font-size: 12px;
    color: #94a3b8;
}

.mention-action {
    opacity: 0;
    transition: opacity 0.2s ease;
    color: #3b82f6;
}

.mention-item:hover .mention-action {
    opacity: 1;
}

.action-icon {
    font-size: 16px;
}

.search-highlight {
    background: #fef3c7;
    color: #92400e;
    padding: 1px 2px;
    border-radius: 3px;
    font-weight: 600;
}

.mention-no-results {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px 16px;
    color: #64748b;
    text-align: center;
}

.no-results-icon {
    font-size: 24px;
    color: #94a3b8;
    margin-bottom: 8px;
}

.no-results-text {
    font-size: 14px;
    font-weight: 500;
    margin-bottom: 4px;
}

.no-results-tip {
    font-size: 12px;
    color: #94a3b8;
}
.comment-item-skeleton { display: flex; align-items: center; gap: 10px; padding: 10px 0; }

/* 输入框外观微调 */
.comment-input :deep(.el-textarea__inner) {
    border-radius: 10px;
}

/* 移动端输入框优化 */
@media (max-width: 768px) {
    .comment-input {
        position: relative;
        z-index: 10;
    }
    
    .comment-input :deep(.el-textarea__inner) {
        font-size: 16px; /* 防止iOS缩放 */
        border-radius: 12px;
        padding: 12px;
        line-height: 1.5;
        /* 确保光标正确显示 */
        caret-color: #3b82f6;
        /* 防止输入框被键盘遮挡 */
        position: relative;
        z-index: 1000;
    }
    
    .comment-section {
        margin-bottom: 20px;
        /* 确保评论区域在移动端有足够的空间 */
        min-height: 200px;
        /* 移动端增加底部间距，确保提交按钮不被遮挡 */
        padding-bottom: 80px;
    }
    
    /* 移动端工作内容区域优化 */
    .work-content-container {
        height: calc(100% - 20px);
        padding: 12px;
        margin: 8px;
        border-radius: 8px;
    }
    
    .work-items-container {
        max-height: calc(100% - 80px);
        min-height: 200px;
        /* 移动端工作项网格优化 */
        display: block;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
    }
    
    /* 移动端工作项样式优化 */
    .work-item-grid {
        grid-template-columns: 1fr;
        gap: 8px;
    }
    
    .work-item {
        margin-bottom: 8px;
        padding: 12px;
        /* 移动端工作项内容优化 */
        font-size: 14px;
        line-height: 1.5;
    }
    
    /* 移动端工作内容标题优化 */
    .content-title {
        font-size: 18px;
        margin-bottom: 12px;
    }
    
    /* 移动端工作内容头部优化 */
    .work-content-header {
        margin-bottom: 12px;
        padding-bottom: 8px;
    }
    
    /* 移动端新增日报时，工作内容区域优化 */
    .new-report-mode .work-content-container {
        height: calc(100% - 10px);
        margin: 4px;
    }
    
    .new-report-mode .work-items-container {
        max-height: calc(100% - 60px);
        min-height: 150px;
    }
    
    /* 确保输入框在移动端有足够的可见空间 */
    .comment-input :deep(.el-textarea) {
        margin-bottom: 10px;
    }
    
    /* 移动端评论输入区域优化 */
    .comment-input {
        padding-bottom: 20px;
    }
    
    .comment-input :deep(.el-textarea__inner) {
        min-height: 80px;
    }
    
    /* 移动端@提及列表优化 */
    .mention-list {
        max-height: 120px;
        margin-bottom: 24px;
        border-radius: 8px;
        box-shadow: 0 8px 24px rgba(0,0,0,0.15);
    }
    
    .mention-item {
        padding: 6px 10px;
    }
    
    .mention-avatar {
        margin-right: 10px;
    }
    
    .user-avatar {
        width: 28px !important;
        height: 28px !important;
        font-size: 12px;
    }
    
    .mention-name {
        font-size: 13px;
    }
    
    .mention-department {
        font-size: 11px;
    }

    /* 移动端评论区域展开时的额外样式 */
    .comment-section.expanded {
        padding-bottom: 20px;
    }
    
    /* 确保评论区域在移动端不会被遮挡 */
    .comment-section {
        scroll-margin-top: 20px;
    }
    
    /* 移动端评论列表滚动条优化 */
    .comment-list {
        padding-right: 16px; /* 增加右侧内边距 */
        /* 移动端滚动条样式 */
        scrollbar-width: thin;
        scrollbar-color: #3b82f6 #f1f5f9;
    }
    
    .comment-list::-webkit-scrollbar {
        width: 8px; /* 移动端稍微宽一点 */
    }
    
    .comment-list::-webkit-scrollbar-track {
        background: #f1f5f9;
        border-radius: 4px;
    }
    
    .comment-list::-webkit-scrollbar-thumb {
        background: #3b82f6;
        border-radius: 4px;
    }
    
    .comment-list::-webkit-scrollbar-thumb:hover {
        background: #1d4ed8;
    }
    
    /* 移动端评论操作区域优化 */
    .comment-actions {
        position: sticky;
        bottom: 0;
        background: #ffffff;
        padding: 12px 0;
        margin-top: 12px;
        border-top: 1px solid #e5e7eb;
        z-index: 100;
    }
    
    .comment-actions .el-button {
        width: 100%;
        height: 44px;
        font-size: 16px;
        font-weight: 600;
        border-radius: 12px;
        transition: all 0.3s ease;
    }
    
    .comment-actions .el-button:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }
    
    .comment-actions .el-button.is-loading {
        background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
        border-color: #3b82f6;
    }
}

/* 筛选条件样式升级 */
.filter-container {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    padding: 0 10px;
  margin: 0 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    flex-shrink: 0;
}

.filter-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;
    padding: 8px 0;
    transition: all 0.2s ease;
}

.filter-title-section {
    display: flex;
    align-items: center;
}

.filter-icon {
    margin-right: 10px;
    font-size: 18px;
    color: #3b82f6;
}

.filter-title {
    font-size: 16px;
    font-weight: 600;
    color: #1e293b;
}

.filter-toggle-icon {
    font-size: 16px;
    color: #6b7280;
    transition: transform 0.3s ease;
}

.filter-toggle-icon.is-expanded {
    transform: rotate(180deg);
}

/* 展开内容样式 */
.filter-content {
    /*margin-top: 16px;*/
    padding-top: 5px;
    border-top: 1px solid #e2e8f0;
    animation: slideDown 0.3s ease;
}

@keyframes slideDown {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.filter-item {
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin-bottom: 10px;
}

.filter-label {
    font-weight: 600;
    color: #475569;
    font-size: 14px;
    margin-bottom: 4px;
}

.filter-input {
    width: 100%;
}

.filter-input :deep(.el-input__wrapper) {
    border-radius: 8px;
    border: 1px solid #d1d5db;
    transition: all 0.2s ease;
}

.filter-input :deep(.el-input__wrapper:hover) {
    border-color: #3b82f6;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.filter-input :deep(.el-input__wrapper.is-focus) {
    border-color: #3b82f6;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}

.filter-actions {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
    padding: 10px 0;
    border-top: 1px solid #e2e8f0;
    /*margin-top: 20px;*/
}

.clear-btn {
    background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
    border: none;
    border-radius: 8px;
    padding: 10px 20px;
    font-weight: 500;
    transition: all 0.2s ease;
    color: white;
}

.clear-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(75, 85, 99, 0.3);
}

/* 加载遮罩层样式 */
.loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.9);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
    border-radius: 16px;
}

.loading-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
}

.loading-text {
    font-size: 16px;
    color: #3b82f6;
    font-weight: 500;
}

.loading-state {
    text-align: center;
    padding: 40px;
    color: #666;
}

.error-state {
    text-align: center;
    padding: 40px;
    color: #666;
}

.error-state .el-icon {
    color: #f56c6c;
    font-size: 48px;
}

.error-state .el-button {
    margin-top: 16px;
}

/* 评论区已清空 */

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

/* 评论列表基础样式 */
 

 

 

 

 

 

 

 

 

 

 

 

 

 

/* 头像增强对齐 */
 

 

 

/* 空列表占位更优雅 */
 

/* 已移除评论相关样式 */

/* 超小屏幕设备优化 */
@media (max-width: 480px) {
    .daily-report-system {
        height: 100vh;
    }
    
    .sidebar {
        max-height: 35vh;
    }
    
    .content-area {
        height: calc(100vh - 35vh);
        min-height: 65vh;
    }
    
    .work-content-container {
        height: calc(100% - 15px);
        padding: 8px;
        margin: 4px;
    }
    
    .work-items-container {
        max-height: calc(100% - 70px);
        min-height: 180px;
    }
    
    .work-item {
        padding: 10px;
        font-size: 13px;
    }
    
    .content-title {
        font-size: 16px;
    }
    
    .new-report-mode .work-content-container {
        height: calc(100% - 8px);
        margin: 2px;
    }
    
    .new-report-mode .work-items-container {
        max-height: calc(100% - 50px);
        min-height: 120px;
    }
}
</style>
